python列表分组名称,分组依据Python中字典的汇总列表

I have a list of dictionaries which I need to aggregate in Python:

data = [{"startDate": 123, "endDate": 456, "campaignName": "abc", "campaignCfid": 789, "budgetImpressions": 10},

{"startDate": 123, "endDate": 456, "campaignName": "abc", "campaignCfid": 789, "budgetImpressions": 50},

{"startDate": 456, "endDate": 789, "campaignName": "def", "campaignCfid": 123, "budgetImpressions": 80}]

and I'm looking to aggregate based on budgetImpressions.

So the final result should be:

data = [{"startDate": 123, "endDate": 456, "campaignName": "abc", "campaignCfid": 789, "budgetImpressions": 60},

{"startDate": 456, "endDate": 789, "campaignName": "def", "campaignCfid": 123, "budgetImpressions": 80}]

Note every entry with a certain campaignName will always have the same corresponding campaignCfid, startDate and endDate.

Can this be done in Python? I've tried using itertools without much success. Would it be a better approach to use Pandas?

解决方案

Yes, use pandas. It's great. You can use the groupby functionality and aggregate by sums, then convert the output to a list of dicts if that is exactly what you want.

import pandas as pd

data = [{"startDate": 123, "endDate": 456, "campaignName": 'abc',

"campaignCfid": 789, "budgetImpressions": 10},

{"startDate": 123, "endDate": 456, "campaignName": 'abc',

"campaignCfid": 789, "budgetImpressions": 50},

{"startDate": 456, "endDate": 789, "campaignName": 'def',

"campaignCfid": 123, "budgetImpressions": 80}]

df = pd.DataFrame(data)

grouped = df.groupby(['startDate', 'endDate', 'campaignCfid',

'campaignName']).agg(sum)

print grouped.reset_index().to_dict('records')

This prints:

[{'startDate': 123L, 'campaignCfid': 789L, 'endDate': 456L, 'budgetImpressions': 60L, 'campaignName': 'abc'}, {'startDate': 456L, 'campaignCfid': 123L, 'endDate': 789L, 'budgetImpressions': 80L, 'campaignName': 'def'}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值