Stacking keeps several equal-shaped NumPy arrays as separate layers inside one result. It fits repeated measurements, channel data, batches, and other cases where each input has the same positions and the new layer dimension should remain visible.
np.stack() joins arrays along a new axis, so the result has one more dimension than each input. axis=0 puts the input arrays on the first dimension, while axis=-1 places the new dimension at the end.
Use stacking only when every input already has the same shape. If the arrays should extend rows, columns, or another dimension that already exists, np.concatenate() is the better operation.
Related: Concatenate arrays
Related: Reshape an array
Related: Transpose an array
import numpy as np morning = np.array([18, 21, 24]) evening = np.array([15, 19, 23]) by_reading = np.stack((morning, evening), axis=0) by_city = np.stack((morning, evening), axis=-1) print("morning shape:", morning.shape) print("evening shape:", evening.shape) print("by reading:") print(by_reading) print("by reading shape:", by_reading.shape) print("by city:") print(by_city) print("by city shape:", by_city.shape)
Both inputs have shape (3,). axis=0 creates one row per reading, and axis=-1 pairs the corresponding positions.
$ python3 array-stack.py morning shape: (3,) evening shape: (3,) by reading: [[18 21 24] [15 19 23]] by reading shape: (2, 3) by city: [[18 15] [21 19] [24 23]] by city shape: (3, 2)
The stacked arrays have one more dimension than the inputs. The same two (3,) arrays become (2, 3) with axis=0 and (3, 2) with axis=-1.
$ python3 - <<'PY'
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[4, 5, 6]])
try:
np.stack((a, b))
except ValueError as error:
print(f"{type(error).__name__}: {error}")
PY
ValueError: all input arrays must have the same shape
Do not reshape around this error until the new axis meaning is clear. A forced reshape can make unrelated rows or positions look comparable.