Sum array by number in numpy

前端 未结 8 1137
别跟我提以往
别跟我提以往 2020-11-30 08:51

Assuming I have a numpy array like: [1,2,3,4,5,6] and another array: [0,0,1,2,2,1] I want to sum the items in the first array by group (the second array) and obtain n-groups

8条回答
  •  萌比男神i
    2020-11-30 09:24

    A pure python implementation:

    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]
    

提交回复
热议问题