numpy的newaxis属性用于给原先的list增加一个新的维度
Example1
x = np.array([0, 1, 2])
print (x.shape)
输出:(3, ) #代表是一个一维的list
x[:, np.newaxis]
ptint(x)
输出:([0], [1], [2]) # (3,1)矩阵
可以直观的理解为,原先的数据保持在第一个维度,随后newaxis在此基础上增加了一个维度
Example2
x = np.array([0, 1, 2])
x[np.newaxis, :]
print x
输出:([[0, 1, 2]]) #shape:(1,3)
Example3
x = np.array([[1, 2, 3], [5, 6, 7], [9, 10, 11]])
column = x[:, 1]
print (column.shape)
输出:(3, ) #实际为一维的list
为了让搜索列向量时,能够返回列向量
column = x[:, 1][:, np.newaxis]
print (column)
输出:([2], [6], [10]) # (3,1)列向量
如果需要将第二列与第三列合并
X_sub = np.hstack([X[:, 1][:, np.newaxis], X[:, 2][:, np.newaxis]])
print X_sub
输出:([2, 3], [6, 7], [10, 11])
或者采用
X_sub = X[:, [1, 2]]