Every array passed to stack() must have exactly the same shape, since stack() doesn't extend an existing axis, it introduces an entirely new one at the position given by axis and lines up the input arrays along it — stacking a list of 1D arrays with axis=0 produces a 2D array where each input becomes one row. This makes stack() the right tool for combining several separately-computed arrays of identical shape into one higher-dimensional array, such as collecting a batch of individually processed samples.
1Understanding np.stack()
Every array passed to stack() must have exactly the same shape, since stack() doesn't extend an existing axis, it introduces an entirely new one at the position given by axis and lines up the input arrays along it — stacking a list of 1D arrays with axis=0 produces a 2D array where each input becomes one row. This makes stack() the right tool for combining several separately-computed arrays of identical shape into one higher-dimensional array, such as collecting a batch of individually processed samples.
If you need to combine same-shaped arrays into a new leading 'batch' dimension, like preparing individual samples for a machine learning model, np.stack(arrays) with the default axis=0 is exactly that operation.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.stack((a, b)))2Practical Example
Here is a real-world application of np.stack() showing how it is used in production NumPy code.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
stacked = np.stack((a, b), axis=1)
print(stacked)3Best Practices
Follow these guidelines when working with np.stack():
1. Use stack() specifically when you want to introduce a new dimension, such as a batch axis, rather than extend an existing one
2. Make sure every input array has exactly the same shape before calling stack(), since unlike concatenate(), there's no 'all axes except one' flexibility
3. Choose the axis parameter deliberately to control where the new dimension appears in the resulting shape, not just accept the default
Tip: If you need to combine same-shaped arrays into a new leading 'batch' dimension, like preparing individual samples for a machine learning model, np.stack(arrays) with the default axis=0 is exactly that operation.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.stack((a, b)))