Introduction

In this tutorial, we want to join NumPy arrays along different axes. In order to do this, we use the functions hstack(), vstack() and dstack() of NumPy.

Import Libraries

First, we import the following python module:

import numpy as np

Define Data

Let's consider two arrays a and b.

Array a

a = np.array([5,7,8])

print(a)
a.shape

Array b

b = np.array([4,2,1])

print(b)
b.shape

Horizontal Stacking

For stacking a sequence of arrays horizontally (column wise), the NumPy function hstack() can be used. The arrays are joined together along the first axis.

hstacked = np.hstack((a,b))

print(hstacked)
hstacked.shape

Vertical Stacking

For stacking a sequence of arrays vertically (row wise), the NumPy function vstack() can be used. The arrays are joined together along the second axis.

vstacked = np.vstack((a,b))

print(vstacked)
vstacked.shape

Depth Wise Stacking

For stacking a sequence of arrays depth wise, the NumPy function dstack() can be used. The arrays are joined together along the third axis.

dstacked = np.dstack((a,b))

print(dstacked)
dstacked.shape

Conclusion

Congratulations! Now you are one step closer to become an AI Expert. You have seen that it is very easy to join NumPy arrays along different axes. We can simply use the functions hstack(), vstack() and dstack() of NumPy. Try it yourself!

Instagram

Also check out our Instagram page. We appreciate your like or comment. Feel free to share this post with your friends.