Python Numpy vstack() – Stack Arrays Vertically

Python numpy.vstack()

To vertically stack two or more numpy arrays, you can use vstack() function.

vstack() takes tuple of arrays as argument, and returns a single ndarray that is a vertical stack of the arrays in the tuple.

Example 1: numpy.vstack() with two 2D arrays

In this example, we shall take two 2D arrays of size 2×2 and shall vertically stack them using vstack() method.

Python Program

import numpy as np

#initialize arrays
A = np.array([[2, 1], [5, 4]])
B = np.array([[3, 4], [7, 8]])

#vertically stack arrays
output = np.vstack((A, B))

print(output)
Run

Output

[[2 1]
 [5 4]
 [3 4]
 [7 8]]

Example 2: Vertically Stack 1D Numpy Arrays

In this example, we shall take three arrays and stack them vertically.

Python Program

import numpy as np

#initialize arrays
A = np.array([2, 1, 5, 4])
B = np.array([3, 4, 7, 8])
C = np.array([8, 6, 0, 3])

#vertically stack arrays
output = np.vstack((A, B, C))

print(output)
Run

Output

[[2 1 5 4]
 [3 4 7 8]
 [8 6 0 3]]

Summary

In this tutorial of Python Examples, we learned how to stack numpy arrays vertically using vstack() function, with the help of well detailed example programs.