numpy.stack() in Python with example.

In this tutorial, we are going to learn how to use numpy.stack() method in Python with simple programs.

Firstly, this method is mainly used for combining a sequence of equal dimension arrays along with a new axis.

numpy.stack() in Python

Numpy stands for Numerical Python.
By using numpy.stack() method we can join the sequence of the equal size arrays based on the axis value(index value for simple understanding).



array: it is a sequence of array of the same size.

axis: The axis in the consequent array along which the input arrays are sequenced/stacked.

  • the axis defines the index of the new axis in the result.
  • axis=0 indicates the starting dimension.
  • axis=-1 indicates the last dimension.

Example code 1:

import numpy as cp
print'First array list:'
print x
print'Second array list:'
print y
print'joining the two arrays along axis 0:'
print cp.stack((x,y),0)

print 'joining the two arrays along axis 1:'
print cp.stack((x,y),1)
First array list:
[[1 3]
[5 7]]
Second array list:
[[2 4]
[6 8]]
joining the two arrays along axis 0:
[[[1 3]
[5 7]]
[[2 4]
[6 8]]]
joining the two arrays along axis 1:
[[[1 3]
[2 4]]
[[5 7]
[6 8]]]

we will see another code as an example so, It makes you understand In brief.

Example 2:

# Example programme for numpy.stack() in python
import numpy as cp
print("First array is:\n",array1)
print("Second array is:\n",array2)
#joining the two arrays along axis 0
print("resultant array along axis 0:\n",result1)
#joining the two arrays along axis 1
print("resultant array along axis 1:",result2)
First array is:
[0 1 2]
Second array is:
[3 4 5]
resultant array along axis 0:
[[0 1 2]
[3 4 5]]
resultant array along axis 1:
[[0 3]
[1 4]
[2 5]]


also, read rfind method in python

Leave a Reply

Your email address will not be published. Required fields are marked *