0
我有一个数组x
我想访问的具体值,其索引由另一个数组给出。由另一个数组有效索引多维numpy数组
例如,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)
或者高效'×〔idxs [:,0],idxs [:, 1]]'?在这里寻找更多的信息 - http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#purely-integer-array-indexing – Divakar
@Divakar哈哈,每次我发布页面刷新,你已经只是写了:) – Alex