使用重复索引增加Numpy数组

fid*_*eli 15 python indexing numpy

我有一个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.bincountnp.unique操作会产生相同的排序顺序是否存在风险?我错过了一些简单的Numpy操作来解决这个问题吗?

goj*_*omo 18

在numpy> = 1.8中,您还可以使用at添加'universal function'('ufunc')的方法.正如文档所述:

对于加法ufunc,此方法等效于[indices] + = b,除了为多次索引的元素累积结果.

以你的榜样为例:

a = np.zeros(6).astype('int')
b = [3, 2, 5, 2]
Run Code Online (Sandbox Code Playgroud)

......那么......

np.add.at(a, b, 1)
Run Code Online (Sandbox Code Playgroud)

......将离开a......

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

  • 这个解决方案是AFAIK最优雅的一款! (2认同)

Alo*_*hal 6

你做完之后

bbins=np.bincount(b)
Run Code Online (Sandbox Code Playgroud)

为什么不这样做:

a[:len(bbins)] += bbins
Run Code Online (Sandbox Code Playgroud)

(编辑进一步简化.)

  • 在多维案例中是否有类似的方法来实现这一目标? (3认同)