a shot of dev knowledge

Related tags

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 horizontallyi.e., along the row. The only condition is that the shape of all the NumPy arrays must have the same number of dimensions except for 1-D arrays, which can be of any length. Below is a visualization of the hstack() operation on a 1-D and 2-D NumPy array.

hstack() operation on 1-D NumPy arrays

1 of 2

Now, take a look at the code:

import numpy as np

arr1 = np.array([0,0])
arr2 = np.array([1,1])

arr = np.hstack((arr1,arr2))

print(arr)
hstack() operation on NumPy arrays

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 verticallyi.e., along the column axis. The only condition is that the shape of all the NumPy arrays must have the same number of dimensions, except for 1-D arrays which can be of any length.

Below is the visualization of the vstack() operation on a 1-D and 2-D NumPy array.

vstack() operation on 1-D NumPy arrays

1 of 2

Now, take a look at the code:

import numpy as np

arr1 = np.array([ [0,0], [0,0] ])
arr2 = np.array([ [1,1], [1,1] ])

arr = np.vstack((arr1,arr2))

print(arr)
vstack() operation on NumPy arrays

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.

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring