Numpy的fancy indexing简介

fancy indexing概念上很简单:即指传递索引数组以便一次得到多个数组元素。使用fancy indexing时要特别注意的一点是返回数组的shape反映的是索引数组的shape而不是被索引的原数组的shape

e.g. 1 简单情况:一维数组

>>>x = np.array([51 92 14 71 60 20 82 86 74 74])
>>>ind = [3,7,4]
>>>x[ind]
array([71,86,60])

e.g. 2 高级用法:多维数组

>>>X = np.arange(12).reshape((3,4))
>>>X
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>>row = np.array([0, 1, 2])
>>>col = np.array([2, 1, 3])
>>>X[row,col]
array([2, 5, 11]) #第一个元素2代表X[0, 2]
# 在索引中将列向量和行向量结合可以得到二维结果
>>>X[row[:, np.newaxis], col] # 行向量中的每个值与每个列向量配对(用了numpy的broadcasting)
array([[ 2,  1,  3],
       [ 6,  5,  7],
       [10,  9, 11]])

参考资料:
https://jakevdp.github.io/PythonDataScienceHandbook/02.07-fancy-indexing.html

你可能感兴趣的:(Python编程,numpy,python)