Sub topic 12
Concatenating and Stacking
This chapter assumes you can create arrays, read their shape, and reshape them, as covered in earlier chapters. It shows how to join several arrays into one.
Two ways to join arrays
NumPy has two main joining operations. They differ in whether the result gets a new axis.
np.concatenatejoins arrays along an axis that already exists. The number of dimensions stays the same.np.stackjoins arrays along a new axis. The result has one more dimension than each input.
import numpy as np
a = np.arange(6).reshape(2, 3)
print(a) # [[0 1 2]
# [3 4 5]]
print(np.concatenate([a, a], axis=0).shape) # (4, 3)
print(np.concatenate([a, a], axis=1).shape) # (2, 6)
print(np.stack([a, a]).shape) # (2, 2, 3)
print(np.stack([a, a], axis=2).shape) # (2, 3, 2)Both functions take a sequence of arrays as their first argument, not separate arguments. Write np.concatenate([a, b]), not np.concatenate(a, b).
The shape rule
For np.concatenate, every dimension except the joining axis must match. Here two arrays join along rows:
import numpy as np
top = np.ones((2, 3))
bottom = np.zeros((1, 3))
print(np.concatenate([top, bottom], axis=0).shape) # (3, 3)Joining them along axis=1 would fail, because the row counts (2 and 1) differ.
For np.stack, all input arrays must have exactly the same shape.
Convenience functions
Three helpers cover common cases:
| Function | Equivalent | Use |
|---|---|---|
| `np.vstack` | Concatenate along axis 0 (after making 1-D inputs into rows) | Stack rows on top of each other |
| `np.hstack` | Concatenate along axis 1 (axis 0 for 1-D inputs) | Place arrays side by side |
| `np.column_stack` | Treat 1-D inputs as columns | Build a table from several 1-D arrays |
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
print(np.vstack([x, y])) # [[1 2 3]
# [4 5 6]]
print(np.hstack([x, y])) # [1 2 3 4 5 6]
print(np.column_stack([x, y])) # [[1 4]
# [2 5]
# [3 6]]Common errors
- Mismatched dimensions. Concatenating a 1-D array with a 2-D array raises a
ValueError. Reshape first, for examplev.reshape(1, -1)to make a row. - Wrong axis. If the output shape is not what you expected, print the shapes of the inputs and check which axis you named.
- Joining in a loop. Each call allocates a new array and copies all the data. Appending one item at a time inside a loop is slow. Collect the pieces in a Python list and join once at the end.
Exercise
You have p = np.zeros((4, 2)) and q = np.ones((4, 2)). What shape does each call return: np.concatenate([p, q], axis=1) and np.stack([p, q], axis=0)?
Show answer
np.concatenate([p, q], axis=1) returns shape (4, 4), because it extends the existing column axis. np.stack([p, q], axis=0) returns shape (2, 4, 2), because it adds a new leading axis that indexes which array each slice came from.