我有一个数组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)
可以传入
axis0
坐标的iterable和axis1
坐标的iterable。见the Numpy docs here正如@Divakar在注释中指出的,这比使用数组视图(即
相关问题 更多 >
编程相关推荐