The np.vstack() is a numpy library function that returns an array in the vertically stacked order. The vstack stands for a vertical stack. The np.vstack() function returns an array that combines the first array followed by the second array. The np.vstack() function stacks the second array after the first array.
To horizontal stack array elements in Python, use the np.hstack() function.
Let’s see the syntax of the numpy vstack() method.
Syntax
numpy.vstack(tup)
Parameters
The np.vstack() function takes one required arguments as a parameter:
tup: The arrays are passed inside the tuple. From these arrays, the np.vstack() function returns the new array that contains values from the first array, followed by the values from the second array. It is the required argument for returning the vertically stacked array. The np.vstack() function appends the value of the second array to the first array. The arrays should contain the same shape.
Return value
It returns the array. This array consists of all the elements from the first array and is followed by all the elements from the second array.
Python program for returning the vertically stacked array using np.vstack() function
# Importing numpy as np
import numpy as np
# Creating an numpy array called arr1
arr1 = np.array([4, 5, 6])
# Creating an numpy array called arr2
arr2 = np.array([7, 8, 9])
# Creating a vertically stacked array from arr1 and arr2
res = np.vstack((arr1, arr2))
print(res)
Output
[[4 5 6]
[7 8 9]]
In this program, we imported a numpy package that has functions for numerical calculations. Then, we have created two numpy arrays called arr1 and arr2 using the function called np.array(). Then, we passed these two arrays into the vstack function. The np.vstack() function combines array 1 and array 2 vertically and returns a combined array.
Python program for returning the vertically stacked nested array using np.vstack()
# Importing numpy as np
import numpy as np
# Creating an numpy array called arr1
arr1 = np.array([[4], [5], [6]])
# Creating an numpy array called arr2
arr2 = np.array([[7], [8], [9]])
# Creating a vertically stacked array from arr1 and arr2
res = np.vstack((arr1, arr2))
print(res)
Output
[[4]
[5]
[6]
[7]
[8]
[9]]
In this program, two nested arrays are created. These nested arrays are then passed to the np.vstack() function. The np.vstack() function vertically stacks the arr1 with the arr2. Hence, the resultant array is formed by appending the arr2 in the arr1 array. The np.vstack() function is similar to concatenating arr2 with the arr1 using np.concatenate() function.
That’s it for numpy vstack() function.