How to choose the "last working day of the month" in Pandas?

I am trying to multiply a DataFrame, provided that this is the last month. I used:

df['Month_End'] = df.index.is_month_end sample = df[df['Month_End'] == 1] 

It works, but I work with stock market data, so I miss all the cases when the actual end of the month on weekends I need a way to choose the "last working day of the month". "

+5
source share
2 answers

You can create time series with the last working day of each month by going to freq='BM' .

For example, to create a series of the last working days of 2014:

 >>> pd.date_range('1/1/2014', periods=12, freq='BM') [2014-01-31 00:00:00, ..., 2014-12-31 00:00:00] Length: 12, Freq: BM, Timezone: None 

You can then use these timers to subset / reindex your DataFrame.

+5
source

pd. Instead of generating a series, you can also analyze the end of a business month from your datetime index as follows:

 df['BMonthEnd'] = (df.index + pd.offsets.BMonthEnd(1)).day 

Although note that a harmless warning is currently being issued - see http://pandas.pydata.org/pandas-docs/stable/timeseries.html#using-offsets-with-series-datetimeindex

+1
source

Source: https://habr.com/ru/post/1208001/


All Articles