Dawei
Dawei

Reputation: 1066

Extend data time index backward directly in pandas

let's say I have a datetimeindex. (In this example I set the date range manually, but actually, there are lot's of date index, and I can't specify the beginning day manually.)

date_idx = pd.DatetimeIndex(pd.date_range("2000-1-1",periods=3))  
DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03'], dtype='datetime64[ns]', freq='D')

I want to extend the index to 3 days before like below.

DatetimeIndex(['1999-12-29', '1999-12-30', '1999-12-31', '2000-01-01',
               '2000-01-02', '2000-01-03'],
              dtype='datetime64[ns]', freq=None)

I toke a detour and got what I want. Is there any easier way to do that?

later = date_idx.tolist()
begin_day = later[0]
former = pd.date_range(begin_day, periods=3 ).shift(-3).tolist()
result = pd.DatetimeIndex(former + later)

Upvotes: 2

Views: 475

Answers (1)

jezrael
jezrael

Reputation: 862406

You need shift with union:

N = 3
print (date_idx.shift(-N).union(date_idx[N-1:]))
DatetimeIndex(['1999-12-29', '1999-12-30', '1999-12-31', '2000-01-01',
               '2000-01-02', '2000-01-03'],
              dtype='datetime64[ns]', freq='D')

Tested with another DatetimeIndex:

date_idx = pd.DatetimeIndex(pd.date_range("2000-1-1",periods=10))  
print (date_idx)
DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04',
               '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08',
               '2000-01-09', '2000-01-10'],
              dtype='datetime64[ns]', freq='D')

later = date_idx.tolist()
begin_day = later[0]
former = pd.date_range(begin_day, periods=5 ).shift(-5).tolist()
r = pd.DatetimeIndex(former + later)
print (r)
DatetimeIndex(['1999-12-27', '1999-12-28', '1999-12-29', '1999-12-30',
               '1999-12-31', '2000-01-01', '2000-01-02', '2000-01-03',
               '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07',
               '2000-01-08', '2000-01-09', '2000-01-10'],
              dtype='datetime64[ns]', freq=None)

N = 5
print (date_idx.shift(-N).union(date_idx[N-1:]))
DatetimeIndex(['1999-12-27', '1999-12-28', '1999-12-29', '1999-12-30',
               '1999-12-31', '2000-01-01', '2000-01-02', '2000-01-03',
               '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07',
               '2000-01-08', '2000-01-09', '2000-01-10'],
              dtype='datetime64[ns]', freq='D')

Upvotes: 2

Related Questions