python中多项分式的求和计算,Python 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},

]

I tried some steps:

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}

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

解决方案

Using 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

And, the final step, df.to_dict:

d = g.to_dict('r')

d

[{'coffee': 9, 'name': 'A', 'tea': 7}, {'coffee': 5, 'name': 'B', 'tea': 16}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值