Python之numpy高维索引与newaxis的用法

对于高维数组,索引位置上的元素不再是标量而是低一维的数组

例子:

X = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print ('X[:, 3] : ' ,X[:, 3])
print('\n' * 1)  #仅仅是为了打印的时候空出一行,好看。
print('X[:, 3].shape : ', X[:, 3].shape) 

这里写图片描述

再看看下面索引与上面索引的不同之处:

print ('X[:, 3:] : ')
print('\n' * 1) 
print (X[:, 3:])
print('\n' * 1) 
print('X[:, 3:].shape : ', X[:, 3:].shape ) 

这里写图片描述

你加不加多一个冒号就决定了你后面输出的值的shape。

当然你不加冒号,你可以用newaxis的方法来多加一个轴
例子:

X = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print ('X[:, 3] : ' ,X[:, 3][:,np.newaxis])
print('\n' * 1) 
print('X[:, 3].shape : ', X[:, 3][:,np.newaxis].shape) 

你可以试一下啦,跟加冒号是一样的

这里写图片描述

猜你喜欢

转载自blog.csdn.net/maymay_/article/details/80286440