【问题标题】:Summing Values in Dictionary Based on Certain Values根据某些值对字典中的值求和
【发布时间】:2020-09-27 08:09:06
【问题描述】:

我有一个列出日期和价格的字典列表。它看起来像这样:

dict = [{'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 50}, {'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 12}, {'Date':datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]

我想创建一个新的字典列表,将同一日期的所有价格值相加。所以输出看起来像这样:

output_dict = [{'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 62}, {'Date':datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]

我怎样才能做到这一点?

【问题讨论】:

  • 您是否尝试过实现任何东西?发生了什么?
  • 使用 defaultdict 的解决方案正是我所追求的!

标签: python dictionary sum conditional-statements


【解决方案1】:

您可以使用来自collections 模块的Counter:

from collections import Counter 

c = Counter() 

for v in dict:
    c[v['Date']] += v['Price']

output_dict = [{'Date': name, 'Price': count} for name, count in c.items()]

输出:

[{'Date': datetime.datetime(2020, 6, 1, 0, 0), 'Price': 62},
 {'Date': datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]

或者,一种新的方式:

您可以使用Pandas 库来解决这个问题:

像这样安装熊猫:

pip install pandas

那么代码是:

import pandas as pd

output_dict = pd.DataFrame(dict).groupby('Date').agg(sum).to_dict()['Price'] 

输出:

{Timestamp('2020-06-01 00:00:00'): 62, Timestamp('2020-06-02 00:00:00'): 60}

【讨论】:

  • pandas 解决方案非常有效,谢谢! (对于阅读本文的任何新手,我将括号内的“dict”替换为我的初始字典名称)
  • @RTorres 你也可以查看我的Counter 解决方案。那也可以。你不必不接受我的回答。
  • 我明白,感谢您的帮助,但我只能接受一个答案,对我有用的解决方案是 defaultdict 一个。
  • 当然。您是否尝试过使用 Counter 的解决方案?那有什么问题?
【解决方案2】:

使用itertools.groupby的另一种解决方案:

import datetime
from itertools import groupby

dct = [{'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 50}, {'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 12}, {'Date':datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]

out = []
for k, g in groupby(dct, lambda k: k['Date']):
    out.append({'Date': k, 'Price': sum(v['Price'] for v in g)})

print(out)

打印:

[{'Date': datetime.datetime(2020, 6, 1, 0, 0), 'Price': 62}, {'Date': datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]

【讨论】:

    【解决方案3】:

    你可以使用 itertools 的groupby,虽然我相信defaultdict 会更快:

    #sort dicts
    dicts = sorted(dicts, key= itemgetter("Date"))
    
    #get the sum via itertools' groupby
    result = [{"Date" : key,
               "Price" :  sum(entry['Price'] for entry in value)}
              for key,value in 
              groupby(dicts, key = itemgetter("Date"))]
    
    print(result)
    
    [{'Date': datetime.datetime(2020, 6, 1, 0, 0), 'Price': 62},
     {'Date': datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]
    

    【讨论】:

      【解决方案4】:

      使用defaultdict

      import datetime
      from collections import defaultdict
      
      dct = [{'Date': datetime.datetime(2020, 6, 1, 0, 0), 'Price': 50},
             {'Date': datetime.datetime(2020, 6, 1, 0, 0), 'Price': 12},
             {'Date': datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]
      
      sum_up = defaultdict(int)
      for v in dct:
          sum_up[v['Date']] += v['Price']
      
      print([{"Date": k, "Price": v} for k, v in sum_up.items()])
      

      [{'Date': datetime.datetime(2020, 6, 1, 0, 0), 'Price': 62}, {'Date': datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]
      

      【讨论】:

        【解决方案5】:

        这是一个很好的 defaultdict 用例,假设我们的 dict 是 my_dict:

        import datetime
        
        my_dict = [{'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 50},
                   {'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 12},
                   {'Date':datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}]
        

        我们可以像这样使用 defaultdict 来累积价格:

        from collections import defaultdict
        
        new_dict = defaultdict(int)
        
        for dict_ in my_dict:
            new_dict[dict_['Date']] += dict_['Price']
        

        然后我们只是将这个字典重新转换为字典列表!:

        my_dict = [{'Date': date, 'Price': price} for date, price in new_dict.items()]
        

        【讨论】:

          猜你喜欢
          • 2023-03-31
          • 2016-10-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多