2016-07-22 218 views
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) 
+1

或者高效'×〔idxs [:,0],idxs [:, 1]]'?在这里寻找更多的信息 - http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#purely-integer-array-indexing – Divakar

+0

@Divakar哈哈,每次我发布页面刷新,你已经只是写了:) – Alex

回答

3

您可以在axis0坐标的迭代和axis1坐标的迭代通过。请参阅the Numpy docs here

i0, i1 = zip(*idxs) 
x[i0, i1] 

如@Divakar评价所指出的,这是较少的内存比使用阵列的视图即

x[idxs[:, 0], idxs[:, 1]] 
+0

@Divakar是的,你说得对! – Alex

相关问题