Wednesday, 3 October 2018

pandas resample to specific weekday in month

I have a Pandas dataframe where I'd like to resample to every third Friday of the month. Using a mask works, but only if there is a third Friday in every month, which is not the case in my sample set (so the following only works on daily data, not when some third Fridays are missing):

dates = pd.date_range("2018-01-01", "2018-08-31")
dates_df = pd.DataFrame(data=np.random.random(len(dates)), index=dates)
mask = (dates.weekday == 4) & (14 < dates.day) & (dates.day < 22)
dates_df.loc[mask]

Using monthly resample in combination with loffset gives the end of month values with offsetting the index, which is also not what I want:

from pandas.tseries.offsets import WeekOfMonth
dates_df.resample("M", loffset=WeekOfMonth(week=2, weekday=4)).last()

Is there an alternative (preferably using resample) without having to resample to daily values first and then adding a mask (this takes a long time to complete on my dataframe)



from pandas resample to specific weekday in month

No comments:

Post a Comment