Understanding NumPy Array Stacking
Stacking in NumPy refers to joining arrays along a specified axis. The axis
parameter determines the dimension along which the arrays are concatenated. If axis=0
(default), stacking occurs vertically, adding arrays one on top of the other. If axis=1
, stacking occurs horizontally, placing arrays side-by-side. For higher-dimensional arrays, axis
determines the corresponding dimension for stacking.
Key NumPy Functions for Stacking
NumPy offers several functions specifically designed for array stacking:
np.vstack()
(Vertical Stack): This function stacks arrays vertically, meaning it adds arrays one on top of the other. The arrays must have the same number of columns.
import numpy as np
= np.array([1, 2, 3])
a = np.array([4, 5, 6])
b
= np.vstack((a, b))
stacked_array print(stacked_array)
= np.array([[1,2],[3,4]])
c = np.array([[5,6],[7,8]])
d = np.vstack((c,d))
stacked_array_2d print(stacked_array_2d)
np.hstack()
(Horizontal Stack): This function stacks arrays horizontally, placing them side-by-side. The arrays must have the same number of rows.
import numpy as np
= np.array([1, 2, 3])
a = np.array([4, 5, 6])
b
= np.hstack((a, b))
stacked_array print(stacked_array)
= np.array([[1,2],[3,4]])
c = np.array([[5,6],[7,8]])
d = np.hstack((c,d))
stacked_array_2d print(stacked_array_2d)
np.concatenate()
(General Stacking): This is a more general function that allows stacking along any specified axis. It’s highly flexible and can handle a wider range of scenarios.
import numpy as np
= np.array([1, 2, 3])
a = np.array([4, 5, 6])
b
= np.concatenate((a,b), axis=0)
stacked_array_vertical print(stacked_array_vertical)
#Output: [1 2 3 4 5 6]
= np.concatenate((a, b), axis=0)
stacked_array_horizontal print(stacked_array_horizontal)
#Output: [1 2 3 4 5 6]
= np.array([[1,2],[3,4]])
c = np.array([[5,6],[7,8]])
d = np.concatenate((c,d), axis=0)
stacked_array_2d_vertical print(stacked_array_2d_vertical)
#Output:
= np.concatenate((c,d), axis=1)
stacked_array_2d_horizontal print(stacked_array_2d_horizontal)
np.stack()
(Stacking along a New Axis): This function stacks arrays along a new axis, creating a higher-dimensional array.
import numpy as np
= np.array([1, 2, 3])
a = np.array([4, 5, 6])
b
= np.stack((a, b))
stacked_array print(stacked_array)
= np.stack((a,b), axis=1)
stacked_array_axis1 print(stacked_array_axis1)
These examples showcase the versatility of NumPy’s stacking capabilities. Choosing the right function depends on the desired arrangement and the dimensions of the input arrays. Understanding these functions is essential for efficient data manipulation within the NumPy ecosystem.