How to use stacking to join arrays in NumPy
The concept of stacking is one way you can join or concatenate two or more NumPy arrays.
The only difference between stacking and concatenation is that stacking is done along an axis. There are two functions used for this:
hstack()vstack()
Let us see these two functions in detail.
NumPy’s hstack() function
The hstack() function accepts a tuple that contains all the NumPy arrays that need to be joined hstack() operation on a 1-D and 2-D NumPy array.
Now, take a look at the code:
import numpy as nparr1 = np.array([0,0])arr2 = np.array([1,1])arr = np.hstack((arr1,arr2))print(arr)
Explanation:
- On line 1, we import the required package.
- On lines 3 and 4, we create two NumPy array objects.
- On line 6, we join those two arrays along the row axis using the
hstack()function. - On line 8, we print our joined NumPy array.
NumPy’s vstack() function
vstack() also accepts a tuple that contains all the NumPy arrays that need to be joined
Below is the visualization of the vstack() operation on a 1-D and 2-D NumPy array.
Now, take a look at the code:
import numpy as nparr1 = np.array([ [0,0], [0,0] ])arr2 = np.array([ [1,1], [1,1] ])arr = np.vstack((arr1,arr2))print(arr)
Explanation:
- On line 1, we import the required package.
- On lines 3 and 4, we create two NumPy array objects.
- On line 6, we join those two arrays along the column axis using the
vstack()function. - On line 8, we print our joined NumPy array.