检查日期是否为假日[TypeError:必须为整数(假日类型为假日)]

时间:2020-04-27 11:17:03

标签: python pandas time

我用熊猫从csv读取数据。读取数据后,我将日期列从字符串转换为日期格式并删除时间。我想创建一个包含值0和1的新列,该列显示一天是假日(1)还是不是假日(0)。为此,我将时间字符串转换为日期时间,并创建了一个假日日历:

import pandas as pd
from pandas.tseries.offsets import Easter, Day
from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday, AbstractHolidayCalendar

# convert strings to date
data['date'] = pd.to_datetime(data['date'], dayfirst=True, errors='coerce')
# remove time
data['date'] = data['date'].dt.date

# german holidays
class GermanHolidays(AbstractHolidayCalendar):
    rules = [Holiday('New Years Day', month=1, day=1),
             Holiday('Good Fridy', GoodFriday),
             Holiday('Easter Monday', EasterMonday),
             Holiday('Ascension of Christ', month=1, day=1, offset=[Easter(), Day(39)]),
             Holiday('Internation Womens Day', month=3, day=8),
             Holiday('First of May', month=5, day=1),
             Holiday('Whit Monday', month=1, day=1, offset=[Easter(), Day(50)]),
             Holiday('Liberation Day', month=5, day=8),
             Holiday('German Unity Day', month=10,day=3),
             Holiday('First Christmas Day', month=12, day=25),
             Holiday('Second Christmas Day', month=12, day=26)]

cal = GermanHolidays()
holidays = cal.holidays(start = data['date'].min(), end = data['date'].max())

问题出现在最后一行(假日= ...),并且出现以下错误:

TypeError: an integer is required (got type Holiday)

我看过其他使用相同代码的帖子,但无法弄清楚,此错误的原因是什么。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您需要修正这些规则:

rules = [Holiday('New Years Day', month=1, day=1),
         GoodFriday,
         EasterMonday,
         Holiday('Ascension of Christ', month=1, day=1, offset=[Easter(), Day(39)]),
         Holiday('Internation Womens Day', month=3, day=8),
         Holiday('First of May', month=5, day=1),
         Holiday('Whit Monday', month=1, day=1, offset=[Easter(), Day(50)]),
         Holiday('Liberation Day', month=5, day=8),
         Holiday('German Unity Day', month=10,day=3),
         Holiday('First Christmas Day', month=12, day=25),
         Holiday('Second Christmas Day', month=12, day=26)]