基于其他数组中的索引的numpy数组的求和值 [英] Summing values of numpy array based on indices in other array

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

问题描述

假设我有以下数组:

N = 8
M = 4

a = np.zeros(M)
b = np.random.randint(M, size=N) # contains indices for a
c = np.random.rand(N) # contains random values

我想根据b中提供的索引对c的值求和,并将它们存储在a中.为此编写一个循环很简单:

I want to sum the values of c according to the indices provided in b, and store them in a. Writing a loop for this is trivial:

for i, v in enumerate(b):
    a[v] += c[i]

由于N在我的实际问题中会变得很大,所以我想避免使用python循环,但是我不知道如何将其编写为numpy语句.有人可以帮我吗?

Since N can get quite big in my real-world problem I'd like to avoid using python loops, but I can't figure out how to write it as a numpy-statement. Can anyone help me out?

好,下面是一些示例值:

Ok, here some example values:

In [27]: b
Out[27]: array([0, 1, 2, 0, 2, 3, 1, 1])

In [28]: c
Out[28]: 
array([ 0.15517108,  0.84717734,  0.86019899,  0.62413489,  0.24357903,
        0.86015187,  0.85813481,  0.7071174 ])

In [30]: a
Out[30]: array([ 0.77930596,  2.41242955,  1.10377802,  0.86015187])

推荐答案

import numpy as np

N = 8
M = 4
b = np.array([0, 1, 2, 0, 2, 3, 1, 1])
c = np.array([ 0.15517108,  0.84717734,  0.86019899,  0.62413489,  0.24357903, 0.86015187,  0.85813481,  0.7071174 ])

a = ((np.mgrid[:M,:N] == b)[0] * c).sum(axis=1)

返回

array([ 0.77930597,  2.41242955,  1.10377802,  0.86015187])

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

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