通过另一个数组有效地索引多节点numpy数组

2024-10-02 08:19:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组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)

Tags: 函数代码importnumpyforoutputnp数组

热门问题