Reshape a NumPy Array
Turn 6 values in a row into a 2 × 3 grid without copying data, as long as the total stays the same.
- reshape(rows, cols)
- Using -1 to infer a dimension
- flatten() and ravel()
Same data, new shape
The problem
Data often arrives as one long line of numbers, but you need it as a table: 12 monthly values as 4 quarters of 3 months, or 784 pixel values as a 28 × 28 image. Reshaping rearranges the same values into a new shape without copying them one by one.
Think of it like this
Reshaping is like rearranging a row of 6 chairs into 2 rows of 3. The same chairs, in the same order, just laid out differently. You cannot make 2 rows of 4 from 6 chairs.
np.arange(1, 7)🪑 Six chairs in one rowvalues.reshape(2, 3)🔲 Rearranged into 2 rows of 32 × 3 = 6✅ The new layout must use every chair exactly oncematrix📋 [[1 2 3] [4 5 6]]Reshaping changes the dimensions of an array while keeping its values and their order; the new shape must contain exactly the same number of elements.
Key points
np.arange(1, 7)creates the values 1 to 6 in a flat array.values.reshape(2, 3)arranges them as 2 rows of 3; 2 × 3 must equal 6.- The values fill the new shape row by row, keeping their order.
valuesis unchanged;matrixis a new view of the same data.
When should you use it?
- Turning flat data into rows and columns: months into quarters, pixels into images.
- Preparing arrays in the shape a machine learning model expects.
- Flattening a table back into one row with
reshape(-1).
When not to use it
- Changing the number of elements: reshape cannot add or remove values; use slicing or padding.
- Swapping rows and columns: that is a transpose (
.T), not a reshape.
See how it works
Press reshape to view the same 12 values with a different shape. The data in memory never moves, only the way it is read.
Example code
import numpy as np
values = np.arange(1, 7)
matrix = values.reshape(2, 3)
print(matrix)
Result of running the code
[[1 2 3]
[4 5 6]]
Code explanation
Six sequential values can be arranged as two rows by three columns. The requested dimensions must multiply to the original size.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input shape and dtype.
- Try negative, floating-point, and missing values.
- Apply the operation to larger multidimensional arrays and measure performance.
Common mistakes
A shape that does not match the size
2 × 4 = 8, but there are only 6 values.
values.reshape(2, 4) # ValueError
values.reshape(2, 3)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges