BlueQuant
BlueQuant

Reputation: 345

How to increment Index of type Date

I am trying to increment the index by 1 for the following array:

Date          High
2017-02-01    253.20 
2017-02-02    252.42
2017-02-03    252.18
2017-02-06    257.82
2017-02-07    260.00

I know that we can increment date by usingtimedelta(days=1) but this will generate a date which my array may not have. So is there any way to increment the index?

and after incrementing, how can i get the value for that incremented index?

Upvotes: 2

Views: 783

Answers (1)

jezrael
jezrael

Reputation: 862441

Use to_timedelta:

df.index = df.index + pd.to_timedelta(1, unit='D')
print (df)
              High
Date              
2017-02-02  253.20
2017-02-03  252.42
2017-02-04  252.18
2017-02-07  257.82
2017-02-08  260.00

Or is possible use shift:

df = df.shift(1, freq='D')
print (df)
              High
Date              
2017-02-02  253.20
2017-02-03  252.42
2017-02-04  252.18
2017-02-07  257.82
2017-02-08  260.00

EDIT:

For replace DatetimeIndex is possible use rename by dict:

d1 = pd.to_datetime('2017-02-03')
d2 = d1 + pd.to_timedelta(5, unit='D')
df = df.rename(index={d1:d2})
print (df)
              High
Date              
2017-02-01  253.20
2017-02-02  252.42
2017-02-08  252.18
2017-02-06  257.82
2017-02-07  260.00

For select 3. index value:

d1 = df.index[2]
d2 = d1 + pd.to_timedelta(5, unit='D')
df = df.rename(index={d1:d2})
print (df)
              High
Date              
2017-02-01  253.20
2017-02-02  252.42
2017-02-08  252.18
2017-02-06  257.82
2017-02-07  260.00

Upvotes: 3

Related Questions