1.np.newaxis的意思是为数组多加一个轴,但是这个轴加在哪里呢?
import numpy as np
a = np.array([
[[10,11,12],
[13,14,15],
[16,17,18]],
[[19,20,21],
[22,23,24],
[25,26,27]]
])
b=a[:,:,:,np.newaxis]
c=a[:,:,np.newaxis,:]
d=a[:,np.newaxis,:,:]
e=a[np.newaxis,:,:,:]
a = np.array([
[[10,11,12],
[13,14,15],
[16,17,18]],
[[19,20,21],
[22,23,24],
[25,26,27]]
])
b=a[:,:,:,np.newaxis]
c=a[:,:,np.newaxis,:]
d=a[:,np.newaxis,:,:]
e=a[np.newaxis,:,:,:]
f=a[np.newaxis]
print(a.shape) # (2, 3, 3)
print(b.shape) # (2, 3, 3, 1)
print(c.shape) # (2, 3, 1, 3)
print(d.shape) # (2, 1, 3, 3)
print(e.shape) # (1, 2, 3, 3)
print(f.shape)
#
(1, 2, 3, 3)
可以从上述结果看到a本身的shape是(2,3,3),正好对应着a[0:2,0:3,0:3]。如果在第二个3的后面加上np.newwaxis,即a[0:2,0:3,0:3,np.newaxis],那么维度就会变为(2,3,3,1),也即b=
a[0:2,0:3,0:3,0:1],同理可得其他部分的维度输出。
注意,如果写成f这种形式,那么就默认是插入了最前面。