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).

syntax:

numpy.stack(array,axis)

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
x=cp.array([[1,3],[5,7]])
print'First array list:'
print x
print'\n'
y=cp.array([[2,4][6,8]])
print'Second array list:'
print y
print'\n'
print'joining the two arrays along axis 0:'
print cp.stack((x,y),0)
print'\n'

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
array1=cp.array([0,1,2])
print("First array is:\n",array1)
array2=cp.array([3,4,5])
print("Second array is:\n",array2)
#joining the two arrays along axis 0
result1=cp.stack((array1,array2),axis=0)
print("resultant array along axis 0:\n",result1)
#joining the two arrays along axis 1
result2=cp.stack((array1,array2),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