我有一个数组x
,我想访问它的特定值,它的索引由另一个数组给定。
例如,x
是
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
并且索引是Nx2 的阵列
idxs = np.array([[1,2], [4,3], [3,3]])
我想要一个返回x[1,2]、x[4,3]、x[3,3]或[7,23,18]数组的函数。下面的代码实现了这个技巧,但我想为大型数组加快速度,也许可以避免for循环。
import numpy as np
def arrayvalsofinterest(x, idx):
output = np.zeros(idx.shape[0])
for i in range(len(output)):
output[i] = x[tuple(idx[i,:])]
return output
if __name__ == "__main__":
xx = np.arange(25).reshape(5,5)
idxs = np.array([[1,2],[4,3], [3,3]])
print arrayvalsofinterest(xx, idxs)
您可以传入axis0
坐标的可迭代项和axis1
坐标的可遍历项。请参阅此处的Numpy文档。
i0, i1 = zip(*idxs)
x[i0, i1]
正如@Divakar在评论中指出的那样,这比使用阵列视图(即)的内存效率更低
x[idxs[:, 0], idxs[:, 1]]