NumPy Tutorial NumPy Statistics NumPy References

NumPy - vstack() function



The NumPy vstack() function stacks arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N).

Syntax

numpy.vstack(tup)

Parameters

tup Required. Specify sequence of ndarrays to be vertically stacked. The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

Return Value

Returns the array formed by stacking the given arrays.

Example:

In the example below, vstack() function is used to stack two given arrays.

import numpy as np

Arr1 = np.array([[10,20],[30, 40]])
Arr2 = np.array([[50,60],[70, 80]])

#stacking arrays vertically
Arr3 = np.vstack((Arr1, Arr2))

#displaying results
print("Arr1 is:")
print(Arr1)
print("\nArr2 is:")
print(Arr2)
print("\nArr3 is:")
print(Arr3)

The output of the above code will be:

Arr1 is:
[[10 20]
 [30 40]]

Arr2 is:
[[50 60]
 [70 80]]

Arr3 is:
[[10 20]
 [30 40]
 [50 60]
 [70 80]]

Example:

Consider one more example, where two arrays has same shape along all except different first axis.

import numpy as np

Arr1 = np.array([10, 20, 30])
Arr2 = np.array([[40,50,60],[70,80,90]])

#stacking arrays vertically
Arr3 = np.vstack((Arr1, Arr2))

#displaying results
print("Arr1 is:")
print(Arr1)
print("\nArr2 is:")
print(Arr2)
print("\nArr3 is:")
print(Arr3)

The output of the above code will be:

Arr1 is:
[10 20 30]

Arr2 is:
[[40 50 60]
 [70 80 90]]

Arr3 is:
[[10 20 30]
 [40 50 60]
 [70 80 90]]

❮ NumPy - Functions