NumPy Array Reshape
Reshaping lets you rearrange the same array data into a different number of dimensions or a different shape entirely.
Reshaping Arrays
Reshaping means changing the shape of an array - the number of elements along each dimension - without changing the underlying data. As long as the total element count matches, you can rearrange a flat array into rows and columns, or a 2-D array into a stack of smaller 2-D blocks.
Reshape From 1-D to 2-D
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)
# Output:
# [[ 1 2 3]
# [ 4 5 6]
# [ 7 8 9]
# [10 11 12]]Reshape From 1-D to 3-D
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 3, 2)
print(newarr)
# Output:
# [[[ 1 2]
# [ 3 4]
# [ 5 6]]
#
# [[ 7 8]
# [ 9 10]
# [11 12]]]The new shape must account for exactly the same number of elements as the original array. Reshaping 12 elements into (4, 3) works because 4 x 3 = 12, but reshape(3, 3) raises a ValueError because 3 x 3 = 9 does not match 12.
Unknown Dimension With -1
You do not always have to specify every dimension yourself. Pass -1 for one dimension and NumPy calculates its correct size automatically based on the array's length and the dimensions you did specify. You can only use -1 for a single dimension at a time.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 2, -1)
print(newarr)
print(newarr.shape)
# Output:
# [[[ 1 2 3]
# [ 4 5 6]]
#
# [[ 7 8 9]
# [10 11 12]]]
# (2, 2, 3)Exercise: NumPy Array Reshape
What must be true for reshape() to succeed when changing an array's shape?