Numpy 高级索引:在 += 中多次使用相同的索引

din*_*hil 4 python arrays indexing numpy matrix

假设你有以下代码

a = np.ones(8)
pos = np.array([1, 3, 5, 3])

a[pos] # returns array([ 1.,  1.,  1.,  1.]), where the 2nd and 4th el are the same
a[pos] +=1 
Run Code Online (Sandbox Code Playgroud)

最后一条指令返回

array([ 1.,  2.,  1.,  2.,  1.,  2.,  1.,  1.])
Run Code Online (Sandbox Code Playgroud)

但我希望对相同索引的分配进行总结,以便获得

array([ 1.,  2.,  1.,  3.,  1.,  2.,  1.,  1.])
Run Code Online (Sandbox Code Playgroud)

有人已经经历过同样的情况吗?

cs9*_*s95 5

使用 np.add.at

a由 指定的元素的操作数执行无缓冲就地操作indices。对于加法ufunc,此方法等效于a[indices] += b,不同之处在于对被多次索引的元素的结果进行累加。

np.add.at(a, pos, 1)

print(a)
array([ 1.,  2.,  1.,  3.,  1.,  2.,  1.,  1.])
Run Code Online (Sandbox Code Playgroud)

请注意,该功能就地工作。