[Python]新建維度np.newaxis

2020-08-09 10:18:35

作用

大白話說就是增加一個軸.
假設一個變數a:
a.shape --> (2,3,3,1)
a[0].shape --> (3,3,1) #a的第一個維度只取其中一個,相當於第一個維度沒有了
b=a[0][:, :, np.newaxis]
b.shape --> (3, 3, 1, 1)

語法

import numpy as np
x=np.arange(0,10)[:, np.newaxis]

等價替換

y=np.arange(0, 10)
y.shape=(10,1)

範例

import numpy as np
a=np.array([[[[1],[1],[1]],[[2],[2],[2]],[[3],[3],[3]]],[[[4],[4],[4]],[[5],[5],[5]],[[6],[6],[6]]]])
b=a[0][:, :, np.newaxis]
c,d=a.shape,b.shape

ouutput:

print(a)
[[[[1]
   [1]
   [1]]

  [[2]
   [2]
   [2]]

  [[3]
   [3]
   [3]]]


 [[[4]
   [4]
   [4]]

  [[5]
   [5]
   [5]]

  [[6]
   [6]
   [6]]]]
print(b)
[[[[1]]

  [[1]]

  [[1]]]


 [[[2]]

  [[2]]

  [[2]]]


 [[[3]]

  [[3]]

  [[3]]]]
print(c)
print(d)
(2, 3, 3, 1)
(3, 3, 1, 1)