arr.shapegives the size of each dimension, e.g.(2, 3).arr.reshape(rows, cols)returns the same data in a new shape (the total size must match).- Use
-1to let NumPy work out one dimension. arr.flatten()turns any array into 1-D.
NumPy Shape & Reshape
Change the dimensions of an array.
✍️ 3 exercises + code challenge in this lessonKey Takeaways: NumPy Shape & Reshape
Mastering NumPy Shape & Reshape helps you write clean and reliable NumPy code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
NumPy Shape & Reshape Code Example
NumPyimport numpy as np
arr = np.arange(1, 13)
print(arr.shape)
m = arr.reshape(3, 4)
print(m)
print(m.shape)
print(arr.reshape(2, -1).shape)
(12,) [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] (3, 4) (2, 6)
NumPy Shape & Reshape Practice Exercises
Check what you learned in “NumPy Shape & Reshape”.
Reshape 12 numbers into 3 rows and 4 columns.
m = arr.(3, 4)
What does -1 mean in reshape(2, -1)?
Reshape np.arange(6) into 2 rows and 3 columns and print the shape.
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services