Sum the value of a dictionary based on the difference between two columns in a dataframe - Python

tea_time :

I have a dataframe and a dictionary

 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}}

The output crate a new column value which is the sum of the dictionary'value (counting the months between the start and end date).

 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

I would like also to add a condition but if it's too complicated it's fine.

If the start_date or the end_date, start in the middle of the month then the value of this month will be divided by two.

I appreciate a lot your help!

Bruno Mello :

Try this (I'm assuming your pandas series are datetime):

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)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398331&siteId=1