How to Reshape Array in NumPy: Syntax and Examples
Use the
numpy.reshape() function to change the shape of an array without changing its data. Provide the new shape as a tuple, for example, array.reshape((rows, columns)). The total number of elements must remain the same.Syntax
The basic syntax to reshape a NumPy array is:
array.reshape(new_shape): Returns a new array with the specified shape.new_shapeis a tuple indicating the desired dimensions, e.g., (2, 3) for 2 rows and 3 columns.- The total number of elements before and after reshaping must be the same.
python
reshaped_array = array.reshape(new_shape)
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 array = np.array([1, 2, 3, 4, 5, 6]) reshaped_array = array.reshape((2, 3)) print(reshaped_array)
Output
[[1 2 3]
[4 5 6]]
Common Pitfalls
Common mistakes when reshaping arrays include:
- Trying to reshape to a shape with a different total number of elements, which causes an error.
- Forgetting that
reshapereturns a new array and does not change the original array unless reassigned. - Using
-1incorrectly; it can be used to automatically calculate one dimension but only once.
python
import numpy as np array = np.array([1, 2, 3, 4, 5, 6]) # Wrong: total elements mismatch # reshaped = array.reshape((3, 3)) # This will raise an error # Correct: using -1 to infer dimension reshaped = array.reshape((3, -1)) print(reshaped)
Output
[[1 2]
[3 4]
[5 6]]
Quick Reference
| Function | Description | Example |
|---|---|---|
| reshape | Change array shape without changing data | array.reshape((2, 3)) |
| -1 in reshape | Automatically calculate one dimension | array.reshape((3, -1)) |
| flatten | Convert multi-dimensional array to 1D | array.flatten() |
Key Takeaways
Use numpy.reshape() to change the shape of an array while keeping data intact.
The new shape must have the same total number of elements as the original array.
Use -1 in reshape to let NumPy infer one dimension automatically.
reshape returns a new array; assign it to a variable to keep the result.
Mismatched shapes cause errors, so always check element counts before reshaping.