Merge two or multiple NumPy arrays using hstack(), vstack, dstack

In this tutorial, we will learn how to merge two arrays. We can easily do this by various functions provided by numpy. We have concatenate()hstack(), vstack() and dstack() to get the job done. In this tutorial, we will learn how to play with these functions to easily perform merging. But to manipulate arrays using these functions you must have some basic knowledge about arrays.

concatenate()

This is a very easy method to concatenate/merge any two arrays. This function takes the arrays which need to be merged in as arguments.
But the condition is that all the arrays must have the same dimensions. 
Let’s understand this by an example,

import numpy as np

a1=np.array([[1,3,2,4,5],[6,7,8,9,0]])
a2=np.array([[3,5,4,2,1],[4,1,2,3,2]])

We have imported numpy module to access the arrays. We have declared two, two-dimensional arrays a1 and a2.

print(np.concatenate([a1,a2]))

Here we have used this concatenate() function which takes two arrays a1 and a2 as arguments.
While working with this function, the point to note is that the dimensions of both the arrays are same.

output:
[[1 3 2 4 5]
 [6 7 8 9 0]
 [3 5 4 2 1]
 [4 1 2 3 2]]

hstack()

This function performs merging operation column-wise. It takes arrays needed to be merged as arguments and performs a merging operation.

import numpy as np

a1=np.array([[1,3,2,4,5],[6,7,8,9,0]])
a2=np.array([[3,5,4,2,1],[4,1,2,3,2]])


print(np.hstack([a1,a2]))

here we have used hstack() function to merge the arrays. Here’s also a thing to note, the dimensions of the arrays are the same.

vstack()

This function as the name suggests merge arrays vertically.

import numpy as np

a1=np.array([[1,3,2,4,5],[6,7,8,9,0]])
a2=np.array([3,5,4,2,1])


print(np.vstack([a1,a2]))

here you can see that the arrays we have considered have different dimensions. So, vstack() has no restrictions on the dimensions of arrays.

output:
[[1 3 2 4 5]
 [6 7 8 9 0]
 [3 5 4 2 1]]

So this is how vstack() works.

dstack()

This is an interesting method to merge arrays. This method performs the merge operation index by index. Let’s jump on to an example for quick and better understanding.

import numpy as np

a1=np.array([[1],[4],[7],[10]])
a2=np.array([[2],[5],[8],[11]])
a3=np.array([[3],[6],[9],[12]])


print(np.dstack([a1,a2,a3]))

This function also has a restriction on the dimension of arrays.

output:

[[[ 1 2 3]]

[[ 4 5 6]]

[[ 7 8 9]]

[[10 11 12]]]

So, this is how we can easily merge arrays using numpy functions.

Leave a Reply

Your email address will not be published. Required fields are marked *