I have a dataframe that is a time series and I want to get the cumsum of differences between the CLOSE and SUBMISSION of an issue. However, I want it only to subtract if the CLOSE value is higher than the SUBMISSION value. Here are the data points (sorted by CLOSE), the expected output, and my attempted code:
df = pd.DataFrame({'REF_KEY': [1, 2, 3, 4, 5], 'SUBMISSION': ['2018-08-21', '2018-09-03', '2018-09-07', '2018-09-06', '2018-08-28'], 'CLOSE': ['2018-09-05', '2018-09-12', '2018-09-18', '2018-09-24', '2018-09-27']})
df['CLOSE'] = df['CLOSE'].astype('datetime64[ns]')
df['SUBMISSION'] = df['SUBMISSION'].astype('datetime64[ns]')
For REF_KEY == 1, ACCUM_DATE_DELTA should be the sum of:
- 15 day difference of ('2018-09-05' - '2018-08-21')
- 2 day difference between ('2018-09-05' - '09-03-2018')
- 8 day difference between ('2018-09-05' - '2018-08-28') making it 26
For REF_KEY == 2, you will get the sum of:
- 22 day difference between ('2018-09-12' - '2018-08-21')
- 9 day difference between ('2018-09-12' - '2018-09-03')
- 5 day difference between ('2018-09-12' - '2018-09-07')
- 6 day difference between ('2018-09-12' - '2018-09-06')
- 15 day difference between ('2018-09-12' - '2018-08-28')
So for REF_KEY == 1, you can see that the difference between its close date includes REF_KEY == [3, 4], and that is because the CLOSE is greater than SUBMISSION. Therefore, I had the idea of creating a condition where the CLOSE date has to be more than SUBMISSION date.
df_2 = pd.DataFrame({'REF_KEY': [1, 2, 3, 4, 5],
'SUBMISSION': ['2018-08-21', '2018-09-03', '2018-09-07', '2018-09-06', '2018-08-28'], 'CLOSE': ['2018-09-05', '2018-09-12', '2018-09-18', '2018-09-24', '2018-09-27'], 'ACCUM_DATE_DELTA': [25, 57, 86, 116, 131]})
df_2['CLOSE'] = df['CLOSE'].astype('datetime64[ns]')
df_2['SUBMISSION'] = df['SUBMISSION'].astype('datetime64[ns]')
Attempted code:
df_2['ACCUM_DATE_DELTA'] = df_2['CLOSE']*len(df_2[df_2['CLOSE'] - df_2['SUBMISSION]]['SUBMISSION'].cumsum()) - df_2[df_2['CLOSE'] - df_2['SUBMISSION]]['SUBMISSION'].cumsum()