首页 > 解决方案 > 根据数据框中两列之间的差异对字典的值求和 - Python

问题描述

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

 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。

非常感谢您的帮助!

标签: pythonpandasdate

解决方案


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

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)


推荐阅读