numpy 堆栈与 numpy v 堆栈和 h 堆栈有何不同?

Has*_*eyg 9 python numpy

我知道 numpy hstack 按列堆叠,vstack 按行堆叠。那么numpy stack的作用是什么呢?

G. *_*son 10

主要区别在于np.stack(强调我的)文档:

沿新轴连接一系列数组。

考虑以下数组:

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']]
Run Code Online (Sandbox Code Playgroud)

然后考虑以下结果:

#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)
Run Code Online (Sandbox Code Playgroud)

请注意,在所有情况下,but dstack,两个数组都沿着现有轴连接(轴 0、轴 1,并且 dstack 添加新轴 2)

那么,根据上面的结果,如果我们改用stack,只改变堆叠轴呢?

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)
Run Code Online (Sandbox Code Playgroud)

请注意,这些都是 3 维数组,只是元素的顺序根据它们堆叠的方向而改变