How is numpy stack different from numpy v stack and h stack?

Viewed 2253

I understand that numpy hstack stacks column wise and vstack stacks row wise. Then what is the function of numpy stack?

1 Answers

The key difference is in the documentation for np.stack (emphasis mine):

Join a sequence of arrays along a new axis.

Consider the following arrays:

arr1=np.array([[1,2,3],[7,8,9]])
arr2=np.array([[4,5,6],[10,11,12]])
arr3=np.array([['a','b','c'],['d','e','f']])

[[1 2 3]
 [7 8 9]]

[[ 4  5  6]
 [10 11 12]]

[['a' 'b' 'c']
 ['d' 'e' 'f']]

Then consider the following results:

#stack horizontally on existing axis
np.hstack([arr1,arr2,arr3])

array([['1', '2', '3', '4', '5', '6', 'a', 'b', 'c'],
       ['7', '8', '9', '10', '11', '12', 'd', 'e', 'f']], dtype='<U11')

shape: (2, 9)

#stack vertically on existing axis
np.vstack([arr1,arr2,arr3])

array([['1', '2', '3'],
       ['7', '8', '9'],
       ['4', '5', '6'],
       ['10', '11', '12'],
       ['a', 'b', 'c'],
       ['d', 'e', 'f']], dtype='<U11')

shape: (6, 3)

#stack depth-wise, adding an axis 2
np.dstack([arr1,arr2,arr3])

array([[['1', '4', 'a'],
        ['2', '5', 'b'],
        ['3', '6', 'c']],

       [['7', '10', 'd'],
        ['8', '11', 'e'],
        ['9', '12', 'f']]], dtype='<U11')

shape: (2, 3, 3)

Note that in all cases but dstack, the two arrays are joined along an existing axis (axis 0, axis 1, and dstack adds a new axis 2)

Then, in light of the above results, what if we use stack instead, only changing the stacking axis?

for i in [0,1,2]:
    stacked=np.stack([arr1,arr2,arr3],axis=i)
    print(f'Stacked on axis {i}\n',stacked, '\n',f'array shape:{stacked.shape}','\n')

Stacked on axis 0
 [[['1' '2' '3']
  ['7' '8' '9']]

 [['4' '5' '6']
  ['10' '11' '12']]

 [['a' 'b' 'c']
  ['d' 'e' 'f']]] 
 array shape:(3, 2, 3) 

Stacked on axis 1
 [[['1' '2' '3']
  ['4' '5' '6']
  ['a' 'b' 'c']]

 [['7' '8' '9']
  ['10' '11' '12']
  ['d' 'e' 'f']]] 
 array shape:(2, 3, 3) 

Stacked on axis 2
 [[['1' '4' 'a']
  ['2' '5' 'b']
  ['3' '6' 'c']]

 [['7' '10' 'd']
  ['8' '11' 'e']
  ['9' '12' 'f']]] 
 array shape:(2, 3, 3)

Note that these are all 3 dimensional arrays, only the order of the elements changes based on the direction they are stacked

Related