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