Horizontal (hstack) and Vertical (vstack) Stacking in NumPy
NumPy provides functions to stack arrays either horizontally or vertically. The two main functions used for this purpose are:
- hstack() - Stacks arrays horizontally (column-wise).
- vstack() - Stacks arrays vertically (row-wise).
1. Horizontal Stacking (hstack)
The hstack() function stacks arrays side by side along the second axis.
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. Vertical Stacking (vstack)
The vstack() function stacks arrays on top of each other along the first axis.
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]]
Conclusion
Using hstack() and vstack(), we can easily combine arrays horizontally and vertically. These functions are useful for structuring data in a convenient way for further processing.