numpy.stack () in Python

Arrays | NumPy | Python Methods and Functions

numpy.stack() is used to combine a sequence of arrays with the same dimensions along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis = 0, this will be the first dimension, and if axis = -1, this will be the last dimension.

Syntax: numpy.stack (arrays, axis )

Parameters:
arrays: [array_like] Sequence of arrays of the same shape.
axis: [int] Axis in the resultant array along which the input arrays are stacked.

Return: [stacked ndarray] The stacked array of the input arrays which has one more dimension than the input arrays.

Code # 1:

# Python program explaining
# stack () function

 

import numpy as geek

 
# input array

in_arr1 = geek.array ([ 1 , 2 , 3 ])

print ( "1st Input array:" , in_arr1) 

 

in_arr2 = geek.array ([ 4 , 5 , 6 ])

print ( "2nd Input array: " , in_arr2) 

  
# Stacking two arrays along the 0 axis

out_arr1 = geek.stack ((in_arr1, in_arr2), axis = 0 )

print ( " Output stacked array along axis 0: " , out_arr1)

 
# Stacking two arrays along axis 1

out_arr2 = geek.stack ((in_arr1, in_arr2), axis = 1 )

print ( "Output stacked array along axis 1:" , out_arr2) 

Exit:

 1st Input array : [1 2 3] 2nd Input array: [4 5 6] Output stacked array along axis 0: [[1 2 3] [4 5 6]] Output stacked array along axis 1: [[1 4] [2 5] [3 6]] 

Code # 2:

# Python program explaining
# stack () function

 

import numpy as geek

 
# input array

in_arr1 = geek.array ([[ 1 , 2 , 3 ] , [ - 1 , - 2 , - 3 ]])

print ( " 1st Input array: " , in_arr1) 

 

in_arr2 = geek.array ([[ 4 , 5 , 6 ], [ - 4 , - 5 , - 6 ]])

print ( "2nd Input array:" , in_arr2) 

 
# Stacking two arrays along the 0 axis

out_arr1 = geek.stack ((in_arr1, in_arr2), axis = 0 )

print ( "Output stacked array along axis 0:" , out_arr1)

 
# Stacking two arrays along axis 1

out_arr2 = geek.stack ((in_arr1, in_arr2), axis = 1 )

print ( " Output stacked array along axis 1: " , out_arr2)

 
# Stacking two arrays along the last axis

out_arr3 = geek.stack ((in_arr1, in_arr2), axis = - 1 )

print ( "Output stacked array along last axis:" , out_arr3)

Output:

 1st Input array: [[1 2 3] [-1 -2 -3]] 2nd Input array: [[4 5 6] [-4 -5 -6]] Output stacked array along axis 0 : [[[1 2 3] [-1 -2 -3]] [[4 5 6 ] [-4 -5 -6]]] Output stacked array along axis 1: [[[1 2 3] [4 5 6]] [[-1 -2 -3] [-4 -5 -6]]] Output stacked array along last axis: [[[1 4] [2 5] [3 6]] [[-1 -4] [-2 -5] [-3 -6]]] 




Get Solution for free from DataCamp guru