piRSquared piRSquared - 1 year ago 291
Python Question

extend a pandas datetimeindex by 1 period

consider the


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

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',
dtype='datetime64[ns]', freq='BM')

I've tried

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


  • Not generalized to use frequency of

  • I get a performance warning

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

Answer Source

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

# => 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])
# => 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download