AppDividend
Latest Code Tutorials

np.hstack: How to Stack Array in Horizontal Direction

The np.hstack() is a numpy library function that stacks the arrays horizontally. Hstack stands for the horizontal stack. The resulting array will be single-dimensional if two single-dimensional arrays are horizontally stacked using a hstack() function. The resulting array has the elements from array 1 first and then has the elements from the second array appended at the end. It is similar to concatenating arrays with the axis is 1. This both results in the same result.

Syntax

numpy.hstack(tup)

Arguments

tup: It is the tuple that consists of arrays in which we want to perform the hstack function. In a single-dimensional array, the length of the arrays can be different, but in other cases, both arrays should have the same shape.

Python program for horizontally stacking the one-dimensional array

import numpy as np

# Creating an array named arr1
arr1 = np.array((1, 2, 3))

# Creating an array named arr2
arr2 = np.array((4, 5, 6))

# Printing the shape of the arr1
print(arr1.shape)

# Printing the shape of the arr2
print(arr2.shape)

# Creating the horizontally stacked array
res = np.hstack((arr1, arr2))
print(res)

Output

(3,)
(3,)
[1 2 3 4 5 6]

In this program, we imported numpy for performing numerical operations. First, we created two numpy arrays using np.array(). It creates a numpy array. Then we printed the shape of the two numpy arrays using np.shape. This prints the dimensions of the two arrays.

Then, we horizontally stacked arrays arr1 ans arr2 using the hstack() function. It concatenates arr1 and arr2 horizontally.

Python program for horizontally stacking the two-dimensional array

# Importing Numpy as np
import numpy as np

# Creating an array named arr1
arr1 = np.array([[1, 2, 3], [4, 5, 6]])

# Creating an array named arr2
arr2 = np.array([[7, 8, 9], [10, 11, 12]])

# Printing the shape of the arr1
print(arr1.shape)

# Printing the shape of the arr2
print(arr2.shape)

# Creating the horizontally stacked array
res = np.hstack((arr1, arr2))
print(res)

Output

(2, 3)
(2, 3)
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]

In this program, we created a multi-dimensional array. We have printed the shape of the two numpy arrays. Finally, we have horizontally stacked these multi-dimensional arrays.

That’s it for np.hstack() tutorial.

Related posts

np.concatenate

np.linspace

np.random.normal

np.random.randint

np.pad

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.