【问题标题】:Sum the value of a dictionary based on the difference between two columns in a dataframe - Python根据数据框中两列之间的差异对字典的值求和 - Python
【发布时间】:2020-04-04 01:11:16
【问题描述】:

我有一个数据框和一个字典

 Start_date     End_Date

1 2019-01-16    2019-05-28  
2 2018-06-05    2018-07-31  
3 2019-02-11    2019-04-14  

{'HDD': {'2015-01': 477.6,
  '2016-01': 429.0,
  '2017-01': 593.8,
  '2018-01': 372.1,
  '2019-01': 502.8,
  '2015-02': 457.4,
  '2016-02': 377.6,
  '2017-02': 369.8,
  '2018-02': 469.8,
  '2019-02': 395.5,
  '2015-03': 325.2,
  '2016-03': 370.8,
  '2017-03': 266.1,
  '2018-03': 392.9,
  '2019-03': 297.3,
  '2015-04': 128.6,
  '2016-04': 215.3,
  '2017-04': 176.8,
  '2018-04': 89.8,
  '2019-04': 206.6,
  '2015-05': 24.2,
  '2016-05': 97.4,
  '2017-05': 88.5,
  '2018-05': 41.4,
  '2019-05': 118.1,
  '2015-06': 0.0,
  '2016-06': 0.0,
  '2017-06': 0.0,
  '2018-06': 0.0,
  '2019-06': 0.0,
  '2015-07': 0.0,
  '2016-07': 0.0,
  '2017-07': 0.0,
  '2018-07': 0.0,
  '2019-07': 0.0,
  '2015-08': 0.0,
  '2016-08': 0.0,
  '2017-08': 0.0,
  '2018-08': 0.0,
  '2019-08': 0.0,
  '2015-09': 21.5,
  '2016-09': 0.0,
  '2017-09': 51.4,
  '2018-09': 0.0,
  '2019-09': 0.0,
  '2015-10': 216.5,
  '2016-10': 223.0,
  '2017-10': 109.1,
  '2018-10': 107.4,
  '2019-10': 63.7,
  '2015-11': 321.4,
  '2016-11': 354.8,
  '2017-11': 422.2,
  '2018-11': 332.4,
  '2019-11': 340.3,
  '2015-12': 436.5,
  '2016-12': 516.1,
  '2017-12': 481.9,
  '2018-12': 407.4,
  '2019-12': 407.4}}

输出创建一个新的列值,它是字典值的总和(计算开始日期和结束日期之间的月份)。

 Start_date     End_Date    Value

1 2019-01-16    2019-05-28  760
2 2018-06-05    2018-07-31  803
3 2019-02-11    2019-04-14  200

我也想添加一个条件,但如果它太复杂也没关系。

如果 start_date 或 end_date,从月中开始,那么这个月的值将除以 2。

非常感谢您的帮助!

【问题讨论】:

    标签: python pandas date


    【解决方案1】:

    试试这个(我假设你的熊猫系列是日期时间):

    from datetime import datetime
    def get_sum_values(start_date, end_date, dictionary, start_middle=10, end_middle=20):
       tot = 0
    
       for key in dictionary['HDD'].keys():
           if datetime.strptime(key, '%Y-%m')>=start_date and datetime.strptime(key, '%Y-%m')<=end_date:
                tot+=dictionary['HDD'][key]
       if start_date.dt.day >= start_middle and start_date <= end_middle:
           tot = tot/2
    
       return tot
    
    df['Value'] = df.apply(lambda row: get_sum_values(row['Start_date'], row['End_Date'], dictionary), axis=1)
    
    

    【讨论】:

    • 不幸的是它不起作用,因为字典没有在 tot+= 中定义。我应该用字典的值替换它吗?非常感谢 :) @Bruno Mello
    • 对不起,我在使用 apply 时忘记将字典作为参数传递,只需根据您的字典名称更改字典
    • 我做到了:)。但问题出在函数内部。 tot+=字典 ["HDD"][key]。它找不到字典:(@Bruno Mello
    • 我应该注意到了!对不起。
    • 这需要很长时间,因为数据框很大。@Bruno Mello
    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 2022-11-22
    • 2022-01-17
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2023-01-12
    • 2020-11-13
    相关资源
    最近更新 更多