pandas :检查日期是否为假期并分配布尔值 [英] Pandas: Checking if a date is a holiday and assigning boolean value

查看:84
本文介绍了 pandas :检查日期是否为假期并分配布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有date列的pandas数据框,并且我试图添加一个新的布尔值列,以指示给定的日期是否是假期.

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.

以下是代码,但是它不起作用(所有值均为False),因为类型似乎不同,而且我不知道如何获取熊猫数据框中的日期"为与假期类型相同:

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:

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])

推荐答案

您无需进行任何转换.只是直接比较. pandas非常聪明,可以比较许多不同类型的日期和时间.如果您在日期/时间兼容性方面遇到问题,则必须采用更加深奥的格式.

You don't need to convert anything. Just compare straight up. pandas is 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.

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

结果:

         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

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

Note that July 4, 2015 falls on a Saturday.

这篇关于 pandas :检查日期是否为假期并分配布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆