0

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!

mozway
  • 194,879
  • 13
  • 39
  • 75

2 Answers2

1

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')
mozway
  • 194,879
  • 13
  • 39
  • 75
0

This possibly works:

ts.index.union([ts.index[-1] + pd.offsets.DateOffset(years=x) for x in range(5)])
AsukaMinato
  • 1,017
  • 12
  • 21
  • See how to [format code](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks) on stack overflow – Andrew Sep 14 '22 at 05:20