给定索引处的numpy数组总和 [英] sum numpy array at given indices

查看:78
本文介绍了给定索引处的numpy数组总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要添加向量的值:

a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='d')

到另一个向量的值:

c = np.array([10, 10, 10], dtype='d')

位于另一个数组(大小为a,值为0 <= b[i] < len(c))给出的另一个数组

at position given by another array (of the same size of a, with values 0 <= b[i] < len(c))

b = np.array([2, 0, 1, 0, 2, 0, 1, 1, 0, 2], dtype='int32')

这很容易用伪代码编写:

This is very simple to write in pseudo code:

for I in range(b.shape[0]):
    J = b[I]
    c[J] += a[I]

类似的事情,但是矢量化了(c的长​​度实际上是几百个).

Something like this, but vectorized (length of c is some hundreds in real case).

c[0] += np.sum(a[b==0]) # 27 (10 + 1 + 3 + 5 + 8)
c[1] += np.sum(a[b==1]) # 25 (10 + 2 + 6 + 7)
c[2] += np.sum(a[b==2]) # 23 (10 + 0 + 4 + 9)

我最初的猜测是:

c[b] += a

,但仅将a的最后一个值相加.

but only last values of a are summed.

推荐答案

您可以使用 np.bincount 以获得基于ID的加权总和,然后与c相加,就像这样-

You can use np.bincount to get ID based weighted summations and then add with c, like so -

np.bincount(b,a) + c

这篇关于给定索引处的numpy数组总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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