NumPy Array Shape and Reshape

Lesson 8 of 17

The shape of an array is the number of elements along each dimension. Reshaping changes that layout without changing the data.

Get the shape

Example

Python
import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
print(arr.size)

Output

Plain Text
(2, 4)
8

(2, 4) means 2 rows and 4 columns. size is the total number of elements.

Reshape 1-D to 2-D

Example

Python
import numpy as np

arr = np.arange(1, 13)
print(arr.reshape(4, 3))

Output

Plain Text
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]

Reshape 1-D to 3-D

Example

Python
import numpy as np

arr = np.arange(1, 13)
print(arr.reshape(2, 3, 2))

Output

Plain Text
[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[ 7  8]
  [ 9 10]
  [11 12]]]

The element count must match

You can reshape into any shape whose sizes multiply to the same total. 12 elements fit (3, 4) or (2, 6), but not (5, 3):

Example

Python
import numpy as np

arr = np.arange(12)
try:
    arr.reshape(5, 3)
except ValueError as error:
    print("Error:", error)

Output

Plain Text
Error: cannot reshape array of size 12 into shape (5,3)

Let NumPy work out one dimension

Pass -1 for one dimension and NumPy calculates it for you:

Example

Python
import numpy as np

arr = np.arange(1, 9)
print(arr.reshape(2, -1))

Output

Plain Text
[[1 2 3 4]
 [5 6 7 8]]

Flatten back to 1-D

flatten() turns any array into 1-D and always returns a copy. reshape(-1) and ravel() do the same but return a view when they can, which is faster.

Example

Python
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.flatten())
print(arr.reshape(-1))

Output

Plain Text
[1 2 3 4 5 6]
[1 2 3 4 5 6]