使用重复索引增加Numpy数组 [英] Increment Numpy array with repeated indices

查看:334
本文介绍了使用重复索引增加Numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

(编辑进一步简化。)

这篇关于使用重复索引增加Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆