【问题标题】:sum values of specific keys in a dict字典中特定键的总和值
【发布时间】:2020-03-21 14:26:02
【问题描述】:

我有一个如下所示的字典列表:

source_dict = [{'ppl': 10, 'items': 15, 'airport': 'lax', 'city': 'Los Angeles', 'timestamp': 1, 'region': 'North America', 'country': 'United States'},
{'ppl': 20, 'items': 32, 'airport': 'JFK', 'city': 'New York', 'timestamp': 2, 'region': 'North America', 'country': 'United States'},
{'ppl': 50, 'items': 20, 'airport': 'ABC', 'city': 'London', 'timestamp': 1, 'region': 'Europe', 'country': 'United Kingdom'}... ]

#Gets the list of countries in the dict
countries  = list(set(stats['country'] for stats  in source_dict))

我知道我可以使用 a 集合:

    counter = collections.Counter()

    for d in source_dict:
        counter.update(d)

但是,想要按国家/地区分组并仅获取某些键而不是所有键的总数。

所以结果应该是

{'Country': 'United States', 'p95': 30, 'items':37},
{'Country': 'England', 'ppl': 50, 'items':20},...

我不确定如何将多个键合并到一个计数器中。产生这样的结果

【问题讨论】:

    标签: python python-3.x dictionary collections


    【解决方案1】:

    在熊猫中你可以这样做:

    import io
    import pandas as pd
    
    dff=io.StringIO("""ppl,items,airport,city,timestamp,region,country
    10,15,lax,Los Angeles,1,North America,United States
    20,32,JFK,New York,2,North America,United States
    50,20,ABC,London,1,Europe,United Kingdom""")
    
    df3=pd.read_csv(dff)                                                                                                                                                
    
    df3                                                                                                                                                                 
    
       ppl  items airport         city  timestamp         region         country
    0   10     15     lax  Los Angeles          1  North America   United States
    1   20     32     JFK     New York          2  North America   United States
    2   50     20     ABC       London          1         Europe  United Kingdom
    
    df3.groupby('region').agg({'ppl':'sum', 'items':'sum'})                                                                                                             
    
    #               ppl  items
    #region                   
    #Europe          50     20
    #North America   30     47
    
    

    【讨论】:

    • 我之所以选择这个作为答案,是因为我的很多东西无论如何都会变成一个数据框,但我会在将它放入 DF 之前对其进行聚合。这对我的用例来说是一个很好的解决方案
    【解决方案2】:

    这是使用collections.defaultdictcollections.Counter 的一种方法。

    例如:

    from collections import defaultdict, Counter
    
    source_dict = [{'ppl': 10, 'items': 15, 'airport': 'lax', 'city': 'Los Angeles', 'timestamp': 1, 'region': 'North America', 'country': 'United States'},
    {'ppl': 20, 'items': 32, 'airport': 'JFK', 'city': 'New York', 'timestamp': 2, 'region': 'North America', 'country': 'United States'},
    {'ppl': 50, 'items': 20, 'airport': 'ABC', 'city': 'London', 'timestamp': 1, 'region': 'Europe', 'country': 'United Kingdom'} ]
    
    result = defaultdict(Counter)
    for stats in source_dict:
        result[stats['country']].update(Counter({'ppl': stats['ppl'], "items": stats['items']}))
    
    #result = [{'Country': k, **v} for k, v in result.items()]  #Required output
    print(result) 
    

    输出:

    defaultdict(<class 'collections.Counter'>,
                {'United Kingdom': Counter({'ppl': 50, 'items': 20}),
                 'United States': Counter({'items': 47, 'ppl': 30})})
    

    【讨论】:

    • 这也很好用,如果我没有使用数据框,我会使用它。想知道,计数器只对字段“求和”,你可以修改它吗,例如,求和 1 个键但平均另一个?
    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多