我有一个Numpy数组和一个索引列表,其值我想增加一个.此列表可能包含重复索引,我希望增量与每个索引的重复次数一致.没有重复,命令很简单:
a=np.zeros(6).astype('int')
b=[3,2,5]
a[b]+=1
Run Code Online (Sandbox Code Playgroud)
有了重复,我想出了以下方法.
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
Run Code Online (Sandbox Code Playgroud)
这是最好的方法吗?假设np.bincount和np.unique操作会产生相同的排序顺序是否存在风险?我错过了一些简单的Numpy操作来解决这个问题吗?