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'}]