Sub topic 8
Reshaping, Concatenating and Stacking
This chapter assumes you can create arrays and read shape and ndim. It also assumes you know basic indexing. Reshaping and stacking change an array's shape without changing the values. You will need both to line shapes up for broadcasting in the next chapters.
Reshaping with reshape
reshape returns an array with the same data in a new shape. The total number of elements must stay the same. NumPy reads the elements in row-major order (C order), so the last axis varies fastest.
import numpy as np
a = np.arange(12)
print(a.reshape(3, 4).shape) # (3, 4)
print(a.reshape(2, 6).shape) # (2, 6)
print(a.reshape(2, 2, 3).shape) # (2, 2, 3)You can pass -1 for one dimension. NumPy then works out that size from the element count.
import numpy as np
a = np.arange(12)
b = a.reshape(4, -1)
print(b.shape) # (4, 3)
print(a.reshape(-1, 1).shape) # (12, 1)reshape returns a view when it can, so the result often shares memory with the original. Editing one can change the other. Call .copy() if you need independent data.
A shape that does not match the element count raises a ValueError.
import numpy as np
a = np.arange(12)
try:
a.reshape(5, 3)
except ValueError as err:
print("error:", err)Flattening
ravel() flattens an array to one dimension and returns a view when possible. flatten() always returns a copy.
import numpy as np
m = np.arange(6).reshape(2, 3)
print(m.ravel()) # [0 1 2 3 4 5]
print(m.T.ravel()) # [0 3 1 4 2 5]The transpose m.T swaps the axes. ravel still reads in row-major order, so the transposed array flattens in a different order.
Concatenating
np.concatenate joins arrays along an axis that already exists. All other dimensions must match.
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
print(np.concatenate([a, b], axis=0))
# [[1 2]
# [3 4]
# [5 6]]
c = np.array([[7], [8]])
print(np.concatenate([a, c], axis=1))
# [[1 2 7]
# [3 4 8]]Joining a (shape (2, 2)) and b (shape (1, 2)) along axis 0 works because the column counts agree. Joining a and b along axis 1 would fail, because the row counts differ (2 and 1).
Stacking
np.stack joins arrays along a new axis. All inputs must have exactly the same shape.
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
print(np.stack([x, y], axis=0).shape) # (2, 3)
print(np.stack([x, y], axis=1).shape) # (3, 2)
print(np.concatenate([x, y]).shape) # (6,)The axis argument says where the new axis goes. With axis=0, each input becomes a row. With axis=1, each input becomes a column. np.vstack and np.hstack are shortcuts for stacking vertically (along rows) and horizontally (along columns).
Common errors
- Wrong element count in reshape. The product of the new shape must equal
a.size. - Mismatched dimensions in concatenate. Every axis except the joining axis must agree.
- Different shapes in stack.
np.stackneeds identical shapes. Useconcatenateif the lengths differ. - Using
raveland expecting a copy. Writing to a raveled view can change the original.
Exercise
You have a = np.arange(6) and b = np.arange(6, 12). Write one expression that produces an array of shape (2, 6), and another that produces an array of shape (12,).
Show answer
np.stack([a, b]) gives shape (2, 6) because stack adds a new axis. np.concatenate([a, b]) gives shape (12,) because it joins along the existing axis. Alternatively, np.vstack([a, b]) also gives (2, 6).
Exercise
An array a has shape (24,). What is the shape of a.reshape(2, -1, 4), and why?
Show answer
The shape is (2, 3, 4). The known sizes multiply to 2 × 4 = 8, and 24 / 8 = 3, so NumPy fills in 3 for the -1.