python - Python 中的字典分组和聚合列表

标签 python list dictionary pandas

我有一个字典列表,我需要用 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}]

我希望根据 budgetImpressions 进行汇总。

所以最后的结果应该是:

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

请注意,每个具有特定事件名称的条目都将始终具有相同的相应事件Cfid、开始日期和结束日期。

这可以用 Python 完成吗?我试过使用 itertools 但没有成功。使用 Pandas 会是更好的方法吗?

最佳答案

只是为了证明有时 python 非常适合做这种事情:

In [11]: from collections import Counter
         from itertools import groupby

In [12]: 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}]

In [13]: g = groupby(data, lambda x: x.pop('campaignName'))

In [14]: d = {}
         for campaign, campaign_data in g:
             c = Counter()
             for row in campaign_data: c.update(row)
             d[campaign] = c  # if you want a dict rather than Counter, return dict(c) here

In [15]: d
Out[15]:
{'abc': Counter({'campaignCfid': 1578, 'endDate': 912, 'startDate': 246, 'budgetImpressions': 60}),
 'def': Counter({'endDate': 789, 'startDate': 456, 'campaignCfid': 123, 'budgetImpressions': 80})}

如果您已经有了这个列表/字典集合,将其提升为 DataFrame 并没有多大意义,留在纯 Python 中通常更便宜。

关于python - Python 中的字典分组和聚合列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24195825/

相关文章:

python - 从不同文件夹导入 Python 模块

python - 使用 pygame 在 python 中使图像背景透明的问题

java - 吉布克斯 : how to remove the word "List" from auto generated java collections?

c++ - 获取对 unordered_map operator[] 返回值的引用

javascript - Javascript 中的 JSON 映射

python - 在 python 中使用 cElementTree 解析 XML

python - 检查值是否在 pyspark 的间隔内

python - 列表中的 x, *y 在 python 中是什么意思

javascript - 你好,你能帮我在 Javascript 中添加最多 5 个列表项选择吗?

python - 如何更改 python 列表字典中的值