我有一个 Numpy 数组和一个索引列表,我想将其值递增 1。该列表可能包含重复索引,我希望增量与每个索引的重复次数成比例。没有重复,命令很简单:
a=np.zeros(6).astype('int')
b=[3,2,5]
a[b]+=1
通过重复,我想出了以下方法。
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 操作来解决这个问题?
最佳答案
在numpy >= 1.8中,还可以使用at
方法添加'通用函数'('ufunc')。作为docs note :
For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once.
以你的例子为例:
a = np.zeros(6).astype('int')
b = [3, 2, 5, 2]
……然后……
np.add.at(a, b, 1)
...将 a
保留为...
array([0, 0, 2, 1, 0, 1])
关于python - 使用重复索引递增 Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2004364/