dartdog
dartdog

Reputation: 10862

Offset date for a Pandas DataFrame date index

Given a Pandas dataframe created as follows:

dates = pd.date_range('20130101',periods=6)
df = pd.DataFrame(np.random.randn(6),index=dates,columns=list('A'))

                  A
2013-01-01   0.847528
2013-01-02   0.204139
2013-01-03   0.888526
2013-01-04   0.769775
2013-01-05   0.175165
2013-01-06  -1.564826

I want to add 15 days to the index. This does not work>

#from pandas.tseries.offsets import *
df.index+relativedelta(days=15)
#df.index + DateOffset(days=5)

TypeError: relativedelta(days=+15)

I seem to be incapable of doing anything right with indexes....

Upvotes: 14

Views: 28656

Answers (3)

jezrael
jezrael

Reputation: 862641

If need convert it to DatetimeIndex and add days use:

df.index = pd.to_datetime(df.index) + pd.Timedelta('15 days')

If already DatetimeIndex:

df.index += pd.Timedelta('15 days')

Upvotes: 0

fantabolous
fantabolous

Reputation: 22716

Marginally shorter/more direct is tshift:

df = df.tshift(15, freq='D')

Link to a list of freq aliases

Upvotes: 10

roman
roman

Reputation: 117380

you can use DateOffset:

>>> df = pd.DataFrame(np.random.randn(6),index=dates,columns=list('A'))
>>> df.index = df.index + pd.DateOffset(days=15)
>>> df
                   A
2013-01-16  0.015282
2013-01-17  1.214255
2013-01-18  1.023534
2013-01-19  1.355001
2013-01-20  1.289749
2013-01-21  1.484291

Upvotes: 25

Related Questions