NumPy vstack()

The vstack() method stacks the given sequence of input arrays vertically.

Example

import numpy as np

array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5], [6, 7]])

# stack the arrays stackedArray = np.vstack((array1, array2))
print(stackedArray) ''' Output [[0 1] [2 3] [4 5] [6 7]] '''

vstack() Syntax

The syntax of vstack() is:

numpy.vstack(tup)

vstack() Arguments

The vstack() method takes a single argument:

  • tup - a tuple of arrays to be stacked

Note: The shape of all arrays in a given tuple must be the same, except the first dimension because we are stacking in axis 0.


vstack() Return Value

The vstack() method returns the vertically stacked array.


Example 1: Vertically Stack Arrays

import numpy as np

array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5], [6, 7]])
array3 = np.array([[8, 9]])

# stack the arrays stackedArray = np.vstack((array1, array2, array3))
print(stackedArray)

Output

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

Example 2: Vertically Stack Arrays of Invalid Shapes

import numpy as np

array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5, 6], [7, 8, 9]])

# stacks the arrays 
stackedArray = np.vstack((array1, array2))

print(stackedArray)

Output

ValueError: all the input array dimensions except 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 3

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges