numpy.vstack() is a function in NumPy used to stack arrays vertically (row-wise). It takes a sequence of arrays as input and returns a single array by stacking them along the vertical axis (axis 0).
Example: Vertical Stacking of 1D Arrays Using numpy.vstack()
Pythonimportnumpyasgeeka=geek.array([1,2,3])print("1st Input array :\n",a)b=geek.array([4,5,6])print("2nd Input array :\n",b)res=geek.vstack((a,b))print("Output vertically stacked array:\n ",res)
Output1st Input array : [1 2 3]2nd Input array : [4 5 6]Output vertically stacked array: [[1 2 3] [4 5 6]]
The two 1D arrays a and b are stacked vertically usingnp.vstack(), combining them into a 2D array where each input array forms a row.
Syntax
numpy.vstack(tup)
Parameters:
- tup:[sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the first axis.
Return:[stacked ndarray] The stacked array of the input arrays.
Vertical Stacking of 2D Arrays Using numpy.vstack()
This code shows how to vertically stack two 2D arrays using numpy.vstack() resulting in a combined 2D array.
Pythonimportnumpyasgeeka=geek.array([[1,2,3],[-1,-2,-3]])print("1st Input array :\n",a)b=geek.array([[4,5,6],[-4,-5,-6]])print("2nd Input array :\n",b)res=geek.vstack((a,b))print("Output stacked array :\n ",res)
Output1st Input array : [[ 1 2 3] [-1 -2 -3]]2nd Input array : [[ 4 5 6] [-4 -5 -6]]Output stacked array : [[ 1 2 3] [-1 -2 -3] [ 4 5 6] [-4 -5 -6]]
Two 2D arrays a and b are vertically stacked, creating a new 2D array where each original array becomes a set of rows in the resulting array.