Python dict分组并求和多个值 [英] Python dict group and sum multiple values
本文介绍了Python dict分组并求和多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在dict格式列表中有一组数据,如下所示:
I have a set of data in the list of dict format like below:
data = [
{'name': 'A', 'tea':5, 'coffee':6},
{'name': 'A', 'tea':2, 'coffee':3},
{'name': 'B', 'tea':7, 'coffee':1},
{'name': 'B', 'tea':9, 'coffee':4},
]
我正在尝试按名称"分组并分别对茶"和咖啡"进行求和
I'm trying to group by 'name' and sum the 'tea' separately and 'coffee' separately
最终分组的数据必须采用以下格式:
The final grouped data must be in the this format:
grouped_data = [
{'name': 'A', 'tea':7, 'coffee':9},
{'name': 'B', 'tea':16, 'coffee':5},
]
我尝试了一些步骤:
from collections import Counter
c = Counter()
for v in data:
c[v['name']] += v['tea']
my_data = [{'name': name, 'tea':tea} for name, tea in c.items()]
for e in my_data:
print e
以上步骤返回了以下输出:
The above step returned the following output:
{'name': 'A', 'tea':7,}
{'name': 'B', 'tea':16}
只有我可以对密钥'tea'求和,我无法对密钥'coffee'求和,请您帮忙解决此问题,以获取grouped_data格式
Only I can sum the key 'tea', I'm not able to get the sum for the key 'coffee', can you guys please help to solve this solution to get the grouped_data format
推荐答案
使用pandas
:
df = pd.DataFrame(data)
df
coffee name tea
0 6 A 5
1 3 A 2
2 1 B 7
3 4 B 9
g = df.groupby('name', as_index=False).sum()
g
name coffee tea
0 A 9 7
1 B 5 16
最后一步,df.to_dict
:
d = g.to_dict('r')
d
[{'coffee': 9, 'name': 'A', 'tea': 7}, {'coffee': 5, 'name': 'B', 'tea': 16}]
这篇关于Python dict分组并求和多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文