How to Use reshape in NumPy: Syntax and Examples
Use
numpy.reshape() to change the shape of an array without changing its data. You provide the new shape as a tuple, and NumPy returns a new array with that shape if possible.Syntax
The reshape function changes the shape of an existing NumPy array. It takes the new shape as a tuple of integers. One dimension can be set to -1 to let NumPy calculate it automatically.
array.reshape(new_shape): returns a new array with the specified shape.new_shape: tuple of integers representing the desired shape.-1innew_shape: automatically calculates the dimension size.
python
numpy.reshape(a, newshape, order='C')Example
This example shows how to reshape a 1D array of 6 elements into a 2D array with 2 rows and 3 columns.
python
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) reshaped_arr = arr.reshape((2, 3)) print(reshaped_arr)
Output
[[1 2 3]
[4 5 6]]
Common Pitfalls
Common mistakes when using reshape include:
- Trying to reshape to a shape that does not match the total number of elements.
- Forgetting that
-1can only be used once in the new shape. - Modifying the original array shape without assigning or using the returned reshaped array.
python
import numpy as np arr = np.array([1, 2, 3, 4]) # Wrong: total elements mismatch # arr.reshape((3, 2)) # Raises ValueError # Right: use compatible shape reshaped = arr.reshape((2, 2)) print(reshaped) # Using -1 to infer dimension auto_reshaped = arr.reshape((-1, 2)) print(auto_reshaped)
Output
[[1 2]
[3 4]]
[[1 2]
[3 4]]
Quick Reference
| Parameter | Description |
|---|---|
| a | Input array to reshape |
| newshape | Tuple specifying the new shape |
| order | 'C' for row-major, 'F' for column-major (default 'C') |
Key Takeaways
Use numpy.reshape() to change an array's shape without changing data.
The new shape must match the total number of elements in the array.
You can use -1 in one dimension to let NumPy calculate it automatically.
reshape() returns a new array; it does not modify the original array in place.
Always ensure the new shape is compatible with the original array size.