What is NumPy Horizontal Stacking?

Horizontal stacking is about placing Numpy arrays next to each other. In NumPy, you can achieve horizontal stacking using the numpy.hstack() function. You can also get the same result by passing axis=1 to concatenate() function.

Syntax for numpy hstack()

np.hstack(tuple)

You pass tuple or list of Numpy arrays to the hstack() function.

Python program to horizontally stack 1-Dimensional Numpy array

import numpy as np
 
x = np.array([1, 2, 3, 4, 5])
y = np.array([16, 17, 18, 19, 20])
print('First array:\n', x)
print('Second array:\n', y)
print('Horizontally stacked array:\n', np.hstack((x, y)))
print('Concatenated 1-D array:\n', np.concatenate([x, y]))

Output

First array:
 [1 2 3 4 5]
Second array:
 [16 17 18 19 20]
Horizontally stacked array:
 [ 1  2  3  4  5 16 17 18 19 20]
Concatenated 1-D array:
 [ 1  2  3  4  5 16 17 18 19 20]

As you can see in the output, np.hstack() has horizontally stacked two Numpy arrays.

Horizontal Stacking of 1-Dimensional Numpy Array

Python program to horizontally stack 2-Dimensional Numpy array

import numpy as np

x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
y = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])
print('First array:\n', x)
print('Second array:\n', y)
print('Horizontally stacked array:\n', np.hstack((x, y)))
print('Concatenated 2-D array:\n', np.concatenate((x,y), axis=1))

Output

First array:
 [[ 1  2  3  4  5]
 [ 6  7  8  9 10]]
Second array:
 [[11 12 13 14 15]
 [16 17 18 19 20]]
Horizontally stacked array:
 [[ 1  2  3  4  5 11 12 13 14 15]
 [ 6  7  8  9 10 16 17 18 19 20]]
Concatenated 2-D array:
 [[ 1  2  3  4  5 11 12 13 14 15]
 [ 6  7  8  9 10 16 17 18 19 20]]

As you can see in the output, horizontal stacking is equivalent to passing axis=1 to concatenate() function.

Horizontal Stacking of 2-Dimensional Numpy Array

Recommended Posts