0

データフレームと辞書があります

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

出力は、ディクショナリの値の合計である新しい列の値をクレートします (開始日と終了日の間の月数をカウントします)。

 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 の日が 15 日を超えている場合は start_date 月の HDD の値を 2 で割り、end_date の日が 28 を下回っている場合は end_date の値を割ります。 2 つの日付の間は 2 で除算されず、start/end_date の月の値のみが除算されます。私のコードは部分的に機能し、end_date を 2 で割ることができますが、start_date の場合は HDD の値全体を取ります。

from datetime import datetime, date, time
import calendar
def get_sum_values(start_date, end_date, dictionary,start_middle=15, end_middle=28):
    tot= 0
    j = 1
    i=1
    difference = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)
    for key in dictionary['HDD'].keys():
        if datetime.strptime(key, '%Y-%m')>=start_date and datetime.strptime(key, '%Y-%m')<=end_date:
            if (i==0 and start_date.day >= start_middle ) or (j==end_date.month and end_date.day<=end_middle):
                tot+=dictionary['HDD'][key]/2
            else:
                tot+=dictionary['HDD'][key]
        #if start_date.dt.day <= start_middle or end_date.dt.day>=end_middle:
                #-dictionary['HDD'][key][end_date]/2
            i+=1
            j+=1
    return tot

gaz['HDD'] = gaz.apply(lambda row: get_sum_values(row['Start_Date'], row['End_Date'],hdd_dict), axis=1)

私はそれが明確であることを願っています。あなたの助けをありがとう:)。

4

1 に答える 1