np.newaxis的用法

参考博客:http://blog.csdn.net/zjm750617105/article/details/53376257

突然看到np.newaxis,,但并不知其用法,一脸懵逼!!

np.newaxis的作用:增加矩阵维度

1、一维


a = np.array([1,2,3,4,5])
a
array([1, 2, 3, 4, 5])
b = a[np.newaxis]
b
array([[1, 2, 3, 4, 5]])
b = a[np.newaxis,:]
b
array([[1, 2, 3, 4, 5]])


默认axis=0

b = a[np.newaxis,:]
b
array([[1, 2, 3, 4, 5]])
b.shape
(1, 5)
b = a[:,np.newaxis]
b
array([[1],
       [2],
       [3],
       [4],
       [5]])
b.shape
(5, 1)

同样的结果:

c = a[None]
c
array([[1, 2, 3, 4, 5]])
c = a[None,:]
a
array([1, 2, 3, 4, 5])
c
array([[1, 2, 3, 4, 5]])
c = a[:,None]
c
array([[1],
       [2],
       [3],
       [4],
       [5]])


2、多维


aa = np.array([[1,2,3,4],[4,5,6,7]])
aa
array([[1, 2, 3, 4],
       [4, 5, 6, 7]])
bb = aa[np.newaxis]
bb
array([[[1, 2, 3, 4],
        [4, 5, 6, 7]]])
aa.shape
(2, 4)
bb.shape
(1, 2, 4)
bb = aa[:,np.newaxis]
bb
array([[[1, 2, 3, 4]],
       [[4, 5, 6, 7]]])
aa
array([[1, 2, 3, 4],
       [4, 5, 6, 7]])
bb.shape
(2, 1, 4)
bb = aa[:,:,np.newaxis]
bb
array([[[1],
        [2],
        [3],
        [4]],
       [[4],
        [5],
        [6],
        [7]]])


同样的:

cc = aa[None]
cc
array([[[1, 2, 3, 4],
        [4, 5, 6, 7]]])
cc = aa[:,:,None]
cc
array([[[1],
        [2],
        [3],
        [4]],
       [[4],
        [5],
        [6],
        [7]]])
cc.shape
(2, 4, 1)
cc = aa[:,None]
cc.shape
(2, 1, 4)
cc
array([[[1, 2, 3, 4]],
       [[4, 5, 6, 7]]])





你可能感兴趣的:(python)