Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list grouping and sum

Suppose I have the following list:

[{'name': 'Amy', 'count': 1}, {'name': 'Amy', 'count': 2}, {'name': 'Peter', 'count': 1}]

How could I group it and sum the count in order to get the following out:

[{'name': 'Amy', 'count': 3}, {'name': 'Peter', 'count': 1}]

Thanks.

like image 866
Pang Avatar asked Jun 13 '26 05:06

Pang


2 Answers

You can use a collecions.Counter:

from collections import Counter
l = [
    {'name': 'Amy', 'count': 1},
    {'name': 'Amy', 'count': 2}, 
    {'name': 'Peter', 'count': 1}
]
c = Counter()
for v in l:
    c[v['name']] += v['count']

Result:

>>> c
Counter({'Amy': 3, 'Peter': 1})
>>> [{'name': name, 'count': count} for name, count in c.items()]
[{'count': 3, 'name': 'Amy'}, {'count': 1, 'name': 'Peter'}]
like image 66
JuniorCompressor Avatar answered Jun 14 '26 18:06

JuniorCompressor


You can alternatively use Pandas groupby function:

df = pd.DataFrame([{'name': 'Amy', 'count': 1},
                   {'name': 'Amy', 'count': 2},
                   {'name': 'Peter', 'count': 1}])

df.groupby("name").sum()

       count
name        
Amy        3
Peter      1
like image 41
jrjc Avatar answered Jun 14 '26 19:06

jrjc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!