reshape()
reshape() rearranges the same numbers into a different grid layout.
In this page:
Syntax
arr.reshape(new_shape)
arr.reshape(rows, -1)
reshape()
reshape gives the same data a new shape as long as the total element count matches. Use -1 for one dimension and NumPy will work it out. When possible the result is a view of the original data.
Note:
Only one dimension can be -1 in a single reshape call.
Example: reshape()
import numpy as np
a = np.arange(12)
print(a.reshape(3, 4))
print(a.reshape(2, -1).shape)
print(a.reshape(2, 2, 3).shape)
# Output:
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# (2, 6)
# (2, 2, 3)
Related Topics
Common Mistakes
- Choosing a shape whose product differs from size
- Using -1 more than once
- Forgetting reshape returns a new array object
Chapter Summary
- reshape keeps the data but changes the shape
- Total size must match
- -1 infers one dimension
- Often returns a view
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: