NumPy vstack()

Summary: in this tutorial, you’ll learn how to use the NumPy vstack() function to vertically join elements of two or more arrays into a single array.

Introduction to the NumPy vstack() function

The vstack() function joins elements of two or more arrays into a single array vertically (row-wise).

Here’s the syntax of the vstack() function:

numpy.vstack((a1,a2,...))Code language: Python (python)

In this syntax, the (a1, a2, …) is a sequence of arrays with the ndarray type.

All arrays a1, a2, .. must have the same shape along all but the first axis. If they’re 1D arrays, then they must have the same length.

NumPy vstack() function examples

Let’s take some examples of using the vstack() function.

1) Using vstack() function to join elements of 1D arrays

The following example uses the vstack() function to join two 1D arrays vertically:

import numpy as np

a = np.array([1, 2])
b = np.array([3, 4])

c = np.vstack((a, b))
print(c)Code language: Python (python)

Output:

[[1 2] 
 [3 4]]Code language: Python (python)
numpy vstack 1d

Note that for 1D arrays, all input arrays must have the same length or you’ll get an error.

The following example attempts to join elements of two 1D arrays with different lengths and causes an error:

import numpy as np

a = np.array([1, 2])
b = np.array([3, 4, 5])

c = np.vstack((a, b))
print(c)Code language: Python (python)

Error:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 2 and the array at index 1 has size 3Code language: Python (python)

2) Using vstack() function to join elements of 2D arrays

The following example uses the vstack() function to join elements of two 2D arrays:

import numpy as np

a = np.array([
    [1, 2],
    [3, 4]
])
b = np.array([
    [5, 6],
    [7, 8]
])

c = np.vstack((a, b))
print(c)Code language: Python (python)
numpy vstack 2d array example

Output:

[[1 2] 
 [3 4] 
 [5 6] 
 [7 8]]Code language: Python (python)

Summary

  • Use the numpy vstack() function to join two or more arrays vertically.
Did you find this tutorial helpful ?