使用NumPy按数字对数组进行求和

30

假设我有一个像这样的numpy数组: [1,2,3,4,5,6] 还有另一个数组: [0,0,1,2,2,1] 我想按组(第二个数组)对第一个数组中的项目进行求和,并按组号顺序获得n组结果(在这种情况下,结果将是[3, 9, 9])。我该如何在numpy中实现此操作?


你为什么需要numpy呢?难道你不只是使用原生的Python列表吗?如果不是,那你使用的是哪种numpy类型? - Matt Ball
2
我需要使用numpy,因为我不想为n个组循环遍历数组n次,因为我的数组大小可能是任意大的。我没有使用Python列表,只是在括号中展示了一个示例数据集。数据类型是int。 - Scribble Master
与https://dev59.com/U1rUa4cB1Zd3GeqPi1iB相关的编程内容。 - TooTone
11个回答

-1
一个纯Python实现:
l = [1,2,3,4,5,6]
g = [0,0,1,2,2,1]

from itertools import izip
from operator import itemgetter
from collections import defaultdict

def group_sum(l, g):
    groups = defaultdict(int)
    for li, gi in izip(l, g):
        groups[gi] += li
    return map(itemgetter(1), sorted(groups.iteritems()))

print group_sum(l, g)

[3, 9, 9]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接