What is NumPy Vertical Stacking?

Vertical stacking is all about placing Numpy arrays on top of each other. In NumPy, you can perform vertical stacking by using the numpy.vstack() function. You can also get the same result by passing axis=0 to concatenate() function.

Syntax for numpy vstack()

np.vstack(tuple)

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

Python program to vertically 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('Vertically stacked array:\n', np.vstack((x, y)))

Output

First array:
 [1 2 3 4 5]
Second array:
 [16 17 18 19 20]
Vertically stacked array:
 [[ 1  2  3  4  5]
 [16 17 18 19 20]]

As you can see in the output, np.vstack() has vertically stacked two 1-D Numpy arrays.

Vertically Stacking of 1-Dimensional Numpy Array

Python program to vertically 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('Vertically stacked array:\n', np.vstack((x, y)))
print('Concatenated 2-D array:\n', np.concatenate((x,y), axis=0))

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]]
Vertically stacked array:
 [[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
Concatenated 2-D array:
 [[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]

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

Vertical Stacking of 2-Dimensional Numpy Array

Recommended Posts