使用重复索引递增 Numpy 数组 [英] Increment Numpy array with repeated indices
问题描述
我有一个 Numpy 数组和一个索引列表,我希望将其值加一.此列表可能包含重复索引,我希望增量随每个索引的重复次数而缩放.没有重复,命令很简单:
I have a Numpy array and a list of indices whose values I would like to increment by one. This list may contain repeated indices, and I would like the increment to scale with the number of repeats of each index. Without repeats, the command is simple:
a=np.zeros(6).astype('int')
b=[3,2,5]
a[b]+=1
通过重复,我想出了以下方法.
With repeats, I've come up with the following method.
b=[3,2,5,2] # indices to increment by one each replicate
bbins=np.bincount(b)
b.sort() # sort b because bincount is sorted
incr=bbins[np.nonzero(bbins)] # create increment array
bu=np.unique(b) # sorted, unique indices (len(bu)=len(incr))
a[bu]+=incr
这是最好的方法吗?假设 np.bincount
和 np.unique
操作会导致相同的排序顺序是否存在风险?我是否缺少一些简单的 Numpy 操作来解决这个问题?
Is this the best way? Is there are risk involved with assuming that the np.bincount
and np.unique
operations would result in the same sorted order? Am I missing some simple Numpy operation to solve this?
推荐答案
之后
bbins=np.bincount(b)
为什么不这样做:
a[:len(bbins)] += bbins
(为进一步简化而编辑.)
(Edited for further simplification.)
这篇关于使用重复索引递增 Numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!