Numpy

Numpy vstack : Stacking Sequences of Numpy Arrays Stepwise

Numpy vstack stacks the different numpy arrays into single numpy array vertically. numpy.vstack(tup) accepts the tuple of arrays as parameter. It returns the stacked array.

1. Numpy vstack Implementation –

Lets understand this step wise.

Step 1:

Lets create at least two numpy array. Use the below code for that.

import numpy
array_1 = numpy.array([ 100, 150, 300] )  
array_2 = numpy.array([ 400, 550, 600] ) 

We have just imported numpy module and create array using numpy.array() function.

Step 2:

In order to stack the two or more numpy array. We will use numpy.vstack() function like below.

out_array = numpy.vstack((array_1, array_2)) 

Here is the complete code.

import numpy
array_1 = numpy.array([ 100, 150, 300] )  
array_2 = numpy.array([ 400, 550, 600] ) 
out_array = numpy.vstack((array_1, array_2)) 
print (out_array)

As we have seen that vstack() returns the out_array.

2. Other Examples for vstack numpy-

2.1  vstack for more than two array-

In the above example, We have stacked two numpy array. But Here we will apply vstack() on four numpy arrays.Actually we can add any number of numpy array in the tuple. The only condition is with it that all numpy array must be same on shape( column wise).

import numpy
array_1 = numpy.array([ 100] )  
array_2 = numpy.array([ 400] ) 
array_3 = numpy.array([ 900] ) 
array_4 = numpy.array([ 500] ) 
out_array = numpy.vstack((array_1, array_2,array_3,array_4)) 
print (out_array)

2.2 numpy.concatenate(tup, axis=0) works same –

vstack does the concatenate operations over the arrays. We can achieve the same using numpy.concatenate(tup, axis=0). Here axis =0 means row wise. 

import numpy
array_1 = numpy.array([ 100] )  
array_2 = numpy.array([ 400] ) 
array_3 = numpy.array([ 900] ) 
array_4 = numpy.array([ 500] ) 
out_array = np.concatenate((array_1, array_2,array_3,array_4), axis=0)
print (out_array)

3. Difference between vstack and hstack –

Both numpy works in the same way with the a difference of axis. The vstack() function stacks the sequence of array vertically and hstack() stacks the horizently. As we have seen the so many example of vstack(). We will see the example of hstack().

import numpy
array_1 = numpy.array([ 100] )  
array_2 = numpy.array([ 400] ) 
array_3 = numpy.array([ 900] ) 
array_4 = numpy.array([ 500] ) 
out_array = numpy.hstack((array_1, array_2,array_3,array_4)) 
print (out_array)
hstack on multiple numpy array

hstack() performs the stacking of the above mentioned arrays horizontally.

Conclusion –

Well , We have done a brief discussion on vstack() and hstack(). We have seen the conceptual way with its implementation. We have seen that how vstack is quite similar with concatenate(). Still If you think something is missing, which should be the part of this article, Please let us know. 

 

Thanks
Data Science Learner Team