What is the function of np.vstack in Python?
The np.vstack function in NumPy is used to stack arrays along the vertical direction (row-wise). Specifically, np.vstack stacks two or more arrays vertically to create a new array.
For example, if there are two 2D arrays, array1 and array2, with the same number of columns, we can use np.vstack([array1, array2]) to stack them together row-wise and create a new 2D array.
import numpy as np
array1 = np.array([[1, 2, 3],
[4, 5, 6]])
array2 = np.array([[7, 8, 9],
[10, 11, 12]])
result = np.vstack([array1, array2])
print(result)
The code above will print the following results:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
In this way, np.vstack can assist us in stacking arrays along the vertical direction while processing arrays.