NumPy Tutorial NumPy Statistics NumPy References

NumPy - hstack() function



The NumPy hstack() function stacks arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.

Syntax

numpy.hstack(tup)

Parameters

tup Required. Specify sequence of ndarrays to be horizontally stacked. The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.

Return Value

Returns the array formed by stacking the given arrays.

Example:

In the example below, hstack() function is used to stack two given arrays.

import numpy as np

Arr1 = np.array([[10,20],[30, 40]])
Arr2 = np.array([[50,60],[70, 80]])

#stacking arrays horizontally
Arr3 = np.hstack((Arr1, Arr2))

#displaying results
print("Arr1 is:")
print(Arr1)
print("\nArr2 is:")
print(Arr2)
print("\nArr3 is:")
print(Arr3)

The output of the above code will be:

Arr1 is:
[[10 20]
 [30 40]]

Arr2 is:
[[50 60]
 [70 80]]

Arr3 is:
[[10 20 50 60]
 [30 40 70 80]]

Example:

Consider one more example, where two arrays has same shape along all except different second axis.

import numpy as np

Arr1 = np.array([[10,20],[30, 40]])
Arr2 = np.array([[50,60,70],[80,90,100]])

#stacking arrays horizontally
Arr3 = np.hstack((Arr1, Arr2))

#displaying results
print("Arr1 is:")
print(Arr1)
print("\nArr2 is:")
print(Arr2)
print("\nArr3 is:")
print(Arr3)

The output of the above code will be:

Arr1 is:
[[10 20]
 [30 40]]

Arr2 is:
[[ 50  60  70]
 [ 80  90 100]]

Arr3 is:
[[ 10  20  50  60  70]
 [ 30  40  80  90 100]]

❮ NumPy - Array Manipulation