TExcelTAD
Home › NumPy › NumPy Array Reshape

NumPy Array Reshape

Reshaping gives the same elements a different shape: twelve values can be a 12-long vector, a 3×4 table, a 2×6 table or a 2×2×3 cube. The values and their order stay the same; only the way they are grouped changes.

python · try it yourself
import numpy as np

months = np.arange(1, 13)        # 1..12
print(months)
quarters = months.reshape(4, 3)  # 4 quarters x 3 months
print(quarters)
halves = months.reshape(2, 2, 3) # 2 halves x 2 quarters x 3 months
print(halves)
[ 1  2  3  4  5  6  7  8  9 10 11 12]
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
[[[ 1  2  3]
  [ 4  5  6]]

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

The size must match

The new shape must contain exactly as many elements as the old one. 12 values fit into (3, 4) but not into (5, 3):

python · try it yourself
import numpy as np

a = np.arange(12)
try:
    a.reshape(5, 3)
except ValueError as err:
    print("ValueError:", err)
ValueError: cannot reshape array of size 12 into shape (5,3)

Let NumPy work out one dimension: -1

You may write -1 for one of the dimensions, and NumPy calculates it from the others. This is extremely common, because you often know the number of columns but not the number of rows:

python · try it yourself
import numpy as np

readings = np.arange(10, 34)          # 24 sensor readings
per_hour = readings.reshape(-1, 6)    # 6 readings per row, rows = 24/6
print(per_hour.shape)
print(per_hour)

column = np.array([1, 2, 3]).reshape(-1, 1)   # turn a vector into a column
print(column.shape)
(4, 6)
[[10 11 12 13 14 15]
 [16 17 18 19 20 21]
 [22 23 24 25 26 27]
 [28 29 30 31 32 33]]
(3, 1)

Flattening back to 1-D

There are three ways to turn any array into a 1-D array:

Method Returns
a.reshape(-1) a view when possible
a.ravel() a view when possible
a.flatten() always a copy
python · try it yourself
import numpy as np

grid = np.array([[1, 2, 3],
                 [4, 5, 6]])
flat_view = grid.ravel()
flat_copy = grid.flatten()

flat_view[0] = 100       # changes grid
flat_copy[1] = 200       # does not
print(grid)
print(flat_view, flat_copy)
[[100   2   3]
 [  4   5   6]]
[100   2   3   4   5   6] [  1 200   3   4   5   6]

Row order vs column order

By default, NumPy reads and fills elements in row-major order ("C order"): the last index changes fastest. Passing order="F" (Fortran/column-major) makes the first index change fastest instead:

python · try it yourself
import numpy as np

a = np.arange(6)
print(a.reshape(2, 3))               # fill row by row
print(a.reshape(2, 3, order="F"))    # fill column by column
[[0 1 2]
 [3 4 5]]
[[0 2 4]
 [1 3 5]]

Adding and removing axes of size 1

Sometimes you need an extra dimension of length 1, for example to turn a 1-D list of values into a single-row table. np.newaxis (an alias of None) inside an index, or np.expand_dims, adds one; np.squeeze removes all size-1 axes:

python · try it yourself
import numpy as np

v = np.array([7, 8, 9])
print(v[np.newaxis, :].shape)        # (1, 3)  row
print(v[:, np.newaxis].shape)        # (3, 1)  column
print(np.expand_dims(v, axis=0).shape)

boxed = np.array([[[5], [6]]])
print(boxed.shape, "->", np.squeeze(boxed).shape)
(1, 3)
(3, 1)
(1, 3)
(1, 2, 1) -> (2,)

Note: reshape returns a view whenever the memory layout allows, so writing to the reshaped array usually writes to the original. Check result.base or use .copy() if you need independence.

Test yourself

What is the shape of np.arange(20).reshape(-1, 4)?

  1. (4, 5)
  2. (5, 4)
  3. (20, 4)
  4. (-1, 4)

Which method always returns a copy?

  1. ravel()
  2. reshape(-1)
  3. flatten()
  4. view()

Can you reshape an array of 10 elements to (3, 3)?

  1. Yes, the extra element is dropped
  2. Yes, it is padded with zeros
  3. No, a ValueError is raised
  4. Yes, but only with order='F'