【发布时间】:2020-11-17 14:26:46
【问题描述】:
假设我有一个 n 维数组 A,其中有一个任意 n:
a = np.arange(3*4*5*...).reshape((3, 4, 5, ...))
...而且我有一个索引数组(正是这个形状或转置的):
ix = np.array([
[0,1,1,...],
[0,0,1,...],
[1,0,1,...],
])
从 ix 的 at 索引中获取元素数组的最快方法是什么?
(例如最快的获取方式:
def take_at(a, ix):
res = np.empty((ix.shape[0],*a.shape[ix.shape[1]:]))
for i in range(ix.shape[0]):
res[i,...] = a[(*ix[i],)]
return res
...仅使用(如果可能的话)numpy 向量化函数/循环/操作?)
用于测试的简单复制粘贴示例::
a = np.arange(3*4*5).reshape((3,4,5))
ix = np.array([
[0,1,1],
[0,0,1],
[1,0,1],
])
def take_at(a, ix):
res = np.empty((ix.shape[0],*a.shape[ix.shape[1]:]), dtype=a.dtype)
for i in range(ix.shape[0]):
res[i,...] = a[(*ix[i],)]
return res
take_at(a, ix)
【问题讨论】:
-
a[ix]不起作用? -
不,a[ix] 像切片一样工作