Slartibartfast
Slartibartfast

Reputation: 1190

How to get the next date avaliable in timeseries dataframe

I have the following list of dates:

DatetimeIndex(['2015-11-19', '2015-12-17', '2015-12-23', '2016-01-19',
               '2016-01-22', '2016-01-29', '2016-02-05', '2016-02-15',
               '2016-02-18', '2016-03-01',
               ...
               '2020-07-17', '2020-07-20', '2020-07-21', '2020-07-28',
               '2020-08-04', '2020-08-18', '2020-09-10', '2020-09-25',
               '2020-09-28', '2020-10-01'],
              dtype='datetime64[ns]', name='Date', length=137, freq=None)

I got these dates from operations on df and I also have df2 which also has these dates but the next date is not timedelta(day=1). Thus for example the first date is 2015-11-19 but the next date could be 2015-11-22. Since the dates are index values, how can i get the next available dates?

Upvotes: 2

Views: 535

Answers (1)

David Erickson
David Erickson

Reputation: 16673

Create a new column equal to the index and .shift() it. Make sure the index is sorted first.

import pandas as pd
df = pd.DataFrame({'Date' : ['2015-11-19', '2015-12-17', '2015-12-23', '2016-01-19',
               '2016-01-22', '2016-01-29', '2016-02-05', '2016-02-15',
               '2016-02-18', '2016-03-01',
               '2020-07-17', '2020-07-20', '2020-07-21', '2020-07-28',
               '2020-08-04', '2020-08-18', '2020-09-10', '2020-09-25',
               '2020-09-28', '2020-10-01']}).set_index('Date')
df['Next Date'] = df.index
df['Next Date'] = df['Next Date'].shift(-1)
df
Out[1]: 
             Next Date
Date                  
2015-11-19  2015-12-17
2015-12-17  2015-12-23
2015-12-23  2016-01-19
2016-01-19  2016-01-22
2016-01-22  2016-01-29
2016-01-29  2016-02-05
2016-02-05  2016-02-15
2016-02-15  2016-02-18
2016-02-18  2016-03-01
2016-03-01  2020-07-17
2020-07-17  2020-07-20
2020-07-20  2020-07-21
2020-07-21  2020-07-28
2020-07-28  2020-08-04
2020-08-04  2020-08-18
2020-08-18  2020-09-10
2020-09-10  2020-09-25
2020-09-25  2020-09-28
2020-09-28  2020-10-01
2020-10-01         NaN

Upvotes: 1

Related Questions