Vertically Stack Arrays – NumPy

NumPy – numpy.vstack() – Stack Arrays Vertically

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.

Examples

1. Vertically stack 2D numpy 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 Code Copy

Output

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

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 Code Copy

Output

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

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍