如何在 Pandas 中选择“本月的最后一个工作日”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27218543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I select 'last business day of the month' in Pandas?
提问by hernanavella
I'm trying to subset a DataFrame on the condition that is the last of the month. I used:
我正在尝试在本月最后一天的条件下对 DataFrame 进行子集化。我用了:
df['Month_End'] = df.index.is_month_end
sample = df[df['Month_End'] == 1]
This works, but I'm working with stock market data, so I'm missing all the instances where the actual end of the month is during the weekend, I need a way to select the "last business day of the month".
这有效,但我正在处理股票市场数据,所以我错过了本月实际结束在周末的所有实例,我需要一种方法来选择“本月的最后一个工作日”。
回答by Alex Riley
You can generate a time serieswith the last business day of each month by passing in freq='BM'.
您可以通过传入每个月的最后一个工作日来生成时间序列freq='BM'。
For example, to create a series of the last business days of 2014:
例如,要创建一系列 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 could then use this timeseries to subset/reindex your DataFrame.
然后,您可以使用此时间序列对您的 DataFrame 进行子集/重新索引。
回答by tsando
pd.Instead of generating the series, you can also parse the business month end from your datetime index as this:
pd.In而不是生成系列,您还可以从您的日期时间索引解析营业月末,如下所示:
df['BMonthEnd'] = (df.index + pd.offsets.BMonthEnd(1)).day
Though note this currently throws a harmless warning - see http://pandas.pydata.org/pandas-docs/stable/timeseries.html#using-offsets-with-series-datetimeindex
尽管请注意这目前会引发无害警告 - 请参阅http://pandas.pydata.org/pandas-docs/stable/timeseries.html#using-offsets-with-series-datetimeindex

