python np.newaxis的使用

import numpy as np

b = np.array([1, 2, 3, 4, 5, 6])

#转化为行矩阵  1*6
#等价于 b[np.newaxis,:]
print(b[np.newaxis]) #np.newaxis == None
print(b[None])
x_data=np.linspace(-1,1,300)[:,np.newaxis]


#转化为列矩阵  6*1
print(b[:,np.newaxis])
print(b[:,None])
x_data=np.linspace(-1,1,300)[np.newaxis,:]



'''
对于这个问题还有一种方法,偶然看sidekit源码发现的;

a = np.array([1,2,3])
a
array([1, 2, 3])
b = a[None]
b
array([[1, 2, 3]])
a.shape
(3,)
b.shape
(1, 3)

'''


import numpy as np


a = np.array([[1,2,3,4],
              [5,6,7,8],
              [9,10,11,12]
              ])

#某二行转化为列
row_to_col_un = a[1,:][:,np.newaxis]

#2,3行,转化为列

row1 = a[1,:][:,np.newaxis]
row2 = a[2,:][:,np.newaxis]
row_to_col_uns = np.hstack([row1, row2])
'''
    [[ 5  9]
     [ 6 10]
     [ 7 11]
     [ 8 12]]
'''

#行全部转化为列  用转置
a.T


#2,3行转化为单独的列
a_1 = a[1:3,:,np.newaxis]


#所有的行转化为单列
a_1 = a[:,:,np.newaxis]
'''
    [[[ 1]
      [ 2]
      [ 3]
      [ 4]]
    
     [[ 5]
      [ 6]
      [ 7]
      [ 8]]
    
     [[ 9]
      [10]
      [11]
      [12]]]
'''
 a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
 b = np.array([[[1,1,1],[1,1,1],[1,1,1],[1,1,1]],[[2,2,2],[2,2,2],[2,2,2],[2,2,2]],[[3,3,3],[3,3,3],[3,3,3],[3,3,3]]])
 >>> b
array([[[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]],


       [[2, 2, 2],
        [2, 2, 2],
        [2, 2, 2],
        [2, 2, 2]],


       [[3, 3, 3],
        [3, 3, 3],
        [3, 3, 3],
        [3, 3, 3]]])
>>> np.append(b, a[:,:,None],axis=2)
array([[[ 1,  1,  1,  1],
        [ 1,  1,  1,  2],
        [ 1,  1,  1,  3],
        [ 1,  1,  1,  4]],


       [[ 2,  2,  2,  5],
        [ 2,  2,  2,  6],
        [ 2,  2,  2,  7],
        [ 2,  2,  2,  8]],


       [[ 3,  3,  3,  9],
        [ 3,  3,  3, 10],
        [ 3,  3,  3, 11],
        [ 3,  3,  3, 12]]])
>>> a.ndim
2
>>> a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> b.ndim
3






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值