Stacking Arrays in NumPy
NumPy provides functions to stack arrays along different axes, allowing for efficient array manipulations. The primary stacking functions are:
- hstack()
- vstack()
- dstack()
- column_stack()
- row_stack()
1. hstack()
The hstack() function horizontally stacks arrays (along axis 1).
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) hstacked_arr = np.hstack((arr1, arr2)) print(hstacked_arr)
Output:
[1 2 3 4 5 6]
2. vstack()
The vstack() function vertically stacks arrays (along axis 0).
arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) vstacked_arr = np.vstack((arr1, arr2)) print(vstacked_arr)
Output:
[[1 2 3] [4 5 6]]
3. dstack()
The dstack() function stacks arrays along the third dimension.
arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[5, 6], [7, 8]]) dstacked_arr = np.dstack((arr1, arr2)) print(dstacked_arr)
Output:
[[[1 5] [2 6]] [[3 7] [4 8]]]
4. column_stack()
The column_stack() function stacks 1D arrays as columns into a 2D array.
arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) col_stacked_arr = np.column_stack((arr1, arr2)) print(col_stacked_arr)
Output:
[[1 4] [2 5] [3 6]]
5. row_stack()
The row_stack() function stacks 1D arrays as rows into a 2D array.
arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) row_stacked_arr = np.row_stack((arr1, arr2)) print(row_stacked_arr)
Output:
[[1 2 3] [4 5 6]]
Conclusion
Stacking arrays in NumPy helps in data manipulation and structuring. The hstack() function stacks arrays horizontally, vstack() stacks them vertically, dstack() stacks along the third dimension, while column_stack() and row_stack() provide alternative stacking methods for 1D arrays.