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