我想要做的示例:
import numpy as np
values = np.array([7, 7, 5, 2, 3, 9])
indices = np.array([
np.array([3,5]),
np.array([4]),
np.array([1,2,3])
])
>>> values[indices]
array([
array([2,9]),
array([3]),
array([7,5,2]),
])
是否可以使用矢量化来实现这一目标? 现在我正在使用 for 循环执行此操作,但它可能会变慢。
谢谢!
最佳答案
我们可以将索引连接起来,用这些索引索引到值
,最后再拆分回来 -
idx = np.concatenate(indices)
all_out = values[idx]
lens = list(map(len,indices))
ssidx = np.r_[0,lens].cumsum()
out = [all_out[i:j] for (i,j) in zip(ssidx[:-1],ssidx[1:])]
为了完整起见,这是基于直接索引的版本 -
[values[i] for i in indices]
因此,通过所提出的方法,我们利用切片,从而减少每次迭代的工作量。因此,除了获取 idx 的步骤需要串联提议索引中的所有索引之外,对于索引中索引数组较小的情况也是有意义的。
关于python - 使用不同长度的数组列表索引一维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57474061/