给定索引处的numpy数组总和

编程入门 行业动态 更新时间:2024-10-13 18:20:50
本文介绍了给定索引处的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数组总和

本文发布于:2023-11-30 00:10:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648067.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   总和   索引   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!