Python Numpy高级索引:在+=

Python Numpy高级索引:在+=,python,arrays,numpy,matrix,indexing,Python,Arrays,Numpy,Matrix,Indexing,假设您有以下代码 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 最后一条指令返回 array([ 1., 2., 1., 2., 1., 2., 1., 1.]) 但我希望对相同索引上的作业进行汇总,以便获得 array([ 1., 2.,

假设您有以下代码

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 
最后一条指令返回

array([ 1.,  2.,  1.,  2.,  1.,  2.,  1.,  1.])
但我希望对相同索引上的作业进行汇总,以便获得

array([ 1.,  2.,  1.,  3.,  1.,  2.,  1.,  1.])
有人已经经历过同样的情况吗?

使用

对元素的操作数
a
执行无缓冲就地操作 由
索引指定
。对于添加
ufunc
,此方法等效 到
a[索引]+=b
,除了为元素累积结果 多次编制索引的


请注意该函数在适当的位置工作。

查看
np.add.at
。谢谢,这似乎起到了作用:)@Divakar如果你想写答案,我将删除我的社区wiki。@cᴏʟᴅsᴘᴇᴇᴅ 那将是一个骗局。寻找它。如果有一个“numpy integer index”标记,那么寻找重复项(或者让提问者找到合适的解决方案)会更容易…:D
np.add.at(a, pos, 1)

print(a)
array([ 1.,  2.,  1.,  3.,  1.,  2.,  1.,  1.])