简体   繁体   中英

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

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

Marginally shorter/more direct is tshift :

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

Link to a list of freq aliases

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM