extend a pandas datetimeindex by 1 period

百般思念 提交于 2020-05-28 14:53:14

问题


consider the DateTimeIndex dates

dates = pd.date_range('2016-01-29', periods=4, freq='BM')
dates

DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29'],
              dtype='datetime64[ns]', freq='BM')

I want to extend the index by one period at the frequency attached to the object.


I expect

pd.date_range('2016-01-29', periods=5, freq='BM')

DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29',
               '2016-05-31'],
              dtype='datetime64[ns]', freq='BM')

I've tried

dates.append(dates[[-1]] + pd.offsets.BusinessMonthEnd())

However

  • Not generalized to use frequency of dates
  • I get a performance warning

    PerformanceWarning: Non-vectorized DateOffset being applied to Series or DatetimeIndex


回答1:


The timestamps in your DatetimeIndex already know that they are describing business month ends, so you can simply add 1:

import pandas as pd
dates = pd.date_range('2016-01-29', periods=4, freq='BM')

print(repr(dates[-1]))
# => Timestamp('2016-04-29 00:00:00', offset='BM')

print(repr(dates[-1] + 1))
# => Timestamp('2016-05-31 00:00:00', offset='BM')

You can add the latter to your index using .union:

dates = dates.union([dates[-1] + 1])
print(dates)
# => DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29',
#                   '2016-05-31'],
#                  dtype='datetime64[ns]', freq='BM')

Compared to .append, this retains knowledge of the offset.




回答2:


try this:

In [207]: dates = dates.append(pd.DatetimeIndex(pd.Series(dates[-1] + pd.offsets.BusinessMonthEnd())))

In [208]: dates
Out[208]: DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29', '2016-05-31'], dtype='datetime64[ns]', freq=None)

or using list ([...]) instead of pd.Series():

In [211]: dates.append(pd.DatetimeIndex([dates[-1] + pd.offsets.BusinessMonthEnd()]))
Out[211]: DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29', '2016-05-31'], dtype='datetime64[ns]', freq=None)


来源:https://stackoverflow.com/questions/39516671/extend-a-pandas-datetimeindex-by-1-period

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!