np.stack函数

2018-07-16  本文已影响1581人  yalesaleng

1. 当axis = 0时,

x1 = np.arange(9).reshape((3,3))
x2 = np.arange(10,19,1).reshape((3,3))

y2 = np.stack((x1,x2),axis=0)

输出:
    [[[ 0  1  2]
      [ 3  4  5]
      [ 6  7  8]]

     [[10 11 12]
      [13 14 15]
      [16 17 18]]]
    
    'y2.shape': (2,3,3)

np.stack的官方解释为 对指定axis增加维度,
我们发现y2.shape为(2,3,3),注意x1.shape为(3,3)也可以看做(1,3,3),
当给x1的axis = 0也就是第一维增加一维后就变成了(2,3,3),这刚好是y2.shape,
那x1增加的这个维度的内容用什么来填充呢?当然是x2了!(所以,也要明白的就是x1和x2的shape一定要相同)

2.当axis = 1时,

x1 = np.arange(9).reshape((3,3))
x2 = np.arange(10,19,1).reshape((3,3))

y2 = np.stack((x1,x2),axis=1)

输出:
    [[[ 0  1  2]
      [10 11 12]]

     [[ 3  4  5]
      [13 14 15]]

     [[ 6  7  8]
      [16 17 18]]]
    
    'y2.shape': (3,2,3)

当axis = 1时,对二维平面的行进行增加,所以本来应该是1行的,经过x2填充变成了2行。

3.同理,当axis = 2时,

x1 = np.arange(9).reshape((3,3))
x2 = np.arange(10,19,1).reshape((3,3))

y2 = np.stack((x1,x2),axis=1)

输出:
    [[[ 0 10]
      [ 1 11]
      [ 2 12]]

     [[ 3 13]
      [ 4 14]
      [ 5 15]]

     [[ 6 16]
      [ 7 17]
      [ 8 18]]]
    
    'y2.shape':(3,3,2)
上一篇 下一篇

猜你喜欢

热点阅读