14

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....

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
dartdog
  • 10,432
  • 21
  • 72
  • 121

3 Answers3

25

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
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
  • Great thanks!It seems I did not realize the need to precede the DateOffset with pd. – dartdog Nov 06 '13 at 18:59
  • I was looking a solution for the same issue and this worked perfectly. Thanks! – Alejandro Carrera Jun 24 '21 at 20:48
  • @dartdog Whether you have to use the prefix `pd.` depends on how you imported the functionality. If you did `from pandas import DateOffset`, then you can (and have to) just write `DateOffset`. If you did `import pandas`, then it's `pandas.DateOffset`. – NerdOnTour Dec 21 '21 at 14:13
10

Marginally shorter/more direct is tshift:

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

Link to a list of freq aliases

fantabolous
  • 21,470
  • 7
  • 54
  • 51
  • The above link seems to be broken, perhaps link to this ? http://pandas.pydata.org/pandas-docs/stable/timeseries.html#shifting-lagging – fixxxer Jul 14 '15 at 06:35
  • 1
    Thanks @fixxxer, that's a slightly different link but I've updated the link. – fantabolous Jul 15 '15 at 09:31
  • 1
    Updated link: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases – piedpiper Jul 24 '20 at 18:07
0

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')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252