gr.kr
gr.kr

Reputation: 63

How to lag business months from calendar days in pandas

I would like to lag a timeseries data by business months. For example if the calendar day falls on 7-12-2018 , 1 month lag should be 26-10-2018 ,2,3,months etc...

import pandas as pd
df = pd.date_range('2018-12-07','2018-12-10',freq = 'D')
df.shift(-1 , freq = 'BM')

Expected result

2018-10-26
2018-10-25
2018-10-24

Upvotes: 2

Views: 547

Answers (1)

aces_full
aces_full

Reputation: 131

The pandas time-series module has a useful business day feature called BDay that can help with this.

from pandas.tseries.offsets import BDay
example_day = pd.datetime(2018, 12, 7) # 12/7/2018
shifted_day = example_day - BDay(31) # Shifted by 31 business days

shifted_day # This is now a pandas TimeStamp object
# Timestamp('2018-10-25 00:00:00')

# You can also apply this shift to a Pandas Date Range
df = pd.date_range('2018-12-07','2018-12-10',freq = 'D')
result = df - BDay(31) # Keep in mind that 12/8 -> 12/10 will share the same shift day due to the weekend between them

Upvotes: 3

Related Questions