2016-07-22 120 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

相關問題