How to Use np.stack in NumPy: Syntax and Examples
Use
np.stack to join a sequence of arrays along a new axis. You provide a list of arrays and specify the axis where the new dimension will be added, combining arrays into one higher-dimensional array.Syntax
The basic syntax of np.stack is:
arrays: A sequence (like a list or tuple) of arrays to join. All must have the same shape.axis: An integer specifying the index of the new axis in the result.out: Optional output array to place the result.
python
np.stack(arrays, axis=0, out=None)
Example
This example shows how to stack three 1D arrays along a new axis to create a 2D array.
python
import numpy as np # Create three 1D arrays arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) arr3 = np.array([7, 8, 9]) # Stack arrays along axis 0 (rows) stacked_axis0 = np.stack([arr1, arr2, arr3], axis=0) # Stack arrays along axis 1 (columns) stacked_axis1 = np.stack([arr1, arr2, arr3], axis=1) print('Stacked along axis 0:') print(stacked_axis0) print('\nStacked along axis 1:') print(stacked_axis1)
Output
Stacked along axis 0:
[[1 2 3]
[4 5 6]
[7 8 9]]
Stacked along axis 1:
[[1 4 7]
[2 5 8]
[3 6 9]]
Common Pitfalls
Common mistakes when using np.stack include:
- Trying to stack arrays of different shapes, which causes an error.
- Confusing
np.stackwithnp.concatenate, which joins arrays along an existing axis instead of creating a new one. - Using an
axisvalue outside the valid range, which raises an error.
python
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5]) # Different shape # Wrong: shapes differ, will raise error try: np.stack([arr1, arr2]) except ValueError as e: print(f'Error: {e}') # Correct: arrays have same shape arr2_correct = np.array([4, 5, 6]) stacked = np.stack([arr1, arr2_correct]) print('Stacked arrays with same shape:') print(stacked)
Output
Error: all input arrays must have the same shape
Stacked arrays with same shape:
[[1 2 3]
[4 5 6]]
Quick Reference
Summary tips for using np.stack:
- Use
np.stackto add a new dimension when combining arrays. - All arrays must have the same shape.
- The
axisparameter controls where the new axis appears. - For joining along existing axes, use
np.concatenateinstead.
Key Takeaways
np.stack joins arrays along a new axis, increasing the array's dimensions.
All input arrays must have the same shape to use np.stack.
The axis parameter sets the position of the new dimension in the output.
Use np.concatenate to join arrays along existing axes, not np.stack.
Invalid axis values or mismatched shapes cause errors with np.stack.