NumPy: numpy.vstack() function

numpy.vstack() function

numpy.vstack() function is used to stack arrays vertically (row-wise) to make a single array. It takes a sequence of arrays and joins them vertically. This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N).
This function is useful when you have two or more arrays with the same number of columns, and you want to concatenate them vertically (row-wise). It is also useful to append a single array as a new row to an existing 2D array.

Syntax:

`numpy.vstack(tup)`

Parameters:

Name Description Required /
Optional
tup The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Required

Return value:

stacked : ndarray The array formed by stacking the given arrays.

Example: Horizontal stacking of numpy arrays

``````>>> import numpy as np
>>> x = np.array([3, 5, 7])
>>> y = np.array([5, 7, 9])
>>> np.vstack((x,y))
array([[3, 5, 7],
[5, 7, 9]])
``````

The above code demonstrates how to vertically stack two one-dimensional numpy arrays using np.vstack() function. In this case, two arrays, x and y, containing integer elements [3, 5, 7] and [5, 7, 9], respectively, are stacked vertically using np.vstack() function.
The resulting output of the code is a two-dimensional numpy array with shape (2, 3) where the first row corresponds to the elements in array x and the second row corresponds to the elements in array y.

Pictorial Presentation:

Example: Stack arrays vertically using numpy.vstack()

``````>>> import numpy as np
>>> x = np.array([[3], [5], [7]])
>>> y = np.array([[5], [7], [9]])
>>> np.vstack((x,y))
array([[3],
[5],
[7],
[5],
[7],
[9]])
``````

The above code creates two numpy arrays x and y which contain three rows and one column each. The np.vstack() function is then used to stack the two arrays vertically. The resulting array has six rows and one column. The first three rows are the elements of array x and the next three rows are the elements of array y.

Pictorial Presentation:

Python - NumPy Code Editor:

Previous: hstack()
Next: block()

﻿