Pandas:检查日期是否为假期并分配布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29688899/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:12:59  来源:igfitidea点击:

Pandas: Checking if a date is a holiday and assigning boolean value

pythonpandas

提问by Gopala

I have a pandas data frame with date column, and I am trying to add a new column of boolean values indicating whether a given date is a holiday or not.

我有一个带有日期列的 Pandas 数据框,我正在尝试添加一个新的布尔值列,指示给定日期是否为假日。

Following is the code, but it does not work (all the values are False) because the types seem to be different, and I can't figure out how to get the 'date' in the pandas data frame to be of the same type as the holidays:

以下是代码,但它不起作用(所有值都是 False),因为类型似乎不同,而且我不知道如何将 Pandas 数据框中的“日期”设为相同类型作为假期:

cal = USFederalHolidayCalendar()
holidays = cal.holidays(start=train_df['date'].min(),
                        end=train_df['date'].max()).to_pydatetime()
train_df['holiday'] = train_df['date'].isin(holidays)
print type(train_df['date'][1])
print type(holidays[0])

回答by Jerome Montino

You don't need to convert anything. Just compare straight up. pandasis smart enough to compare a lot of different types with regards to dates and times. You have to have a slightly more esoteric format if you're having issues with date/time compatibility.

你不需要转换任何东西。直接比较就行了。pandas足够聪明,可以比较许多不同类型的日期和时间。如果您遇到日期/时间兼容性问题,则必须使用更深奥的格式。

import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar as calendar

dr = pd.date_range(start='2015-07-01', end='2015-07-31')
df = pd.DataFrame()
df['Date'] = dr

cal = calendar()
holidays = cal.holidays(start=dr.min(), end=dr.max())

df['Holiday'] = df['Date'].isin(holidays)
print df

Result:

结果:

         Date Holiday
0  2015-07-01   False
1  2015-07-02   False
2  2015-07-03    True
3  2015-07-04   False
4  2015-07-05   False
5  2015-07-06   False
6  2015-07-07   False
7  2015-07-08   False
8  2015-07-09   False
9  2015-07-10   False
10 2015-07-11   False
11 2015-07-12   False
12 2015-07-13   False
13 2015-07-14   False
14 2015-07-15   False
15 2015-07-16   False
16 2015-07-17   False
17 2015-07-18   False
18 2015-07-19   False
19 2015-07-20   False
20 2015-07-21   False
21 2015-07-22   False
22 2015-07-23   False
23 2015-07-24   False
24 2015-07-25   False
25 2015-07-26   False
26 2015-07-27   False
27 2015-07-28   False
28 2015-07-29   False
29 2015-07-30   False
30 2015-07-31   False

Note that July 4, 2015 falls on a Saturday.

请注意,2015 年 7 月 4 日是星期六。

回答by Michael Hartman

I had the same problem as the author, and the other fix provided didn't work for me. This is what did work:

我和作者有同样的问题,提供的其他修复对我不起作用。这是什么工作:

train_df['holiday'] = train_df['date'].dt.date.astype('datetime64').isin(holidays)