How to add multiple years to DateTimeIndex in Pandas

Viewed 14

I'd like to add multiple years to my date index in pandas, but have not been able to do so:

ts is a dataframe with a series and relevant dates. I would like to extend those dates by an additional several years in order to add other series for plotting/analysis.

ts.head()

date
2014-12-31         NaN
2015-12-31    0.617876
2016-12-31    0.472640
2017-12-31    0.426240
2018-12-31    0.297176
Name: BL-US, dtype: float64

I've tried

ts.index.union([ts.index[-1] + datetime.timedelta(years=x) for x in range(7)])

and received the following error:

TypeError: 'years' is an invalid keyword argument for new()

Any suggestions? Thank you!

2 Answers

You should use date_range:

ts.index.union(pd.date_range(ts.index[-1], periods=5, freq='Y'))

output:

DatetimeIndex(['2014-12-31', '2015-12-31', '2016-12-31', '2017-12-31',
               '2018-12-31', '2019-12-31', '2020-12-31', '2021-12-31',
               '2022-12-31'],
              dtype='datetime64[ns]', freq='A-DEC')

This possibly works:

ts.index.union([ts.index[-1] + pd.offsets.DateOffset(years=x) for x in range(5)])
Related