gpt4 book ai didi

python - 使用重复索引递增 Numpy 数组

转载 作者:太空狗 更新时间:2023-10-29 17:05:25 25 4
gpt4 key购买 nike

我有一个 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.bincountnp.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com