在使用Pandas假日类创建假日日历时,我无法确定为美国选举日创建日历的适当规则。美国选举日的定义是11月的第一个星期一之后的星期二,每一年都有偶数年发生。使用定义的假日类:
class USElectionCalendar(AbstractHolidayCalendar):
"""
Federal Presidential and Congressional election day.
Tuesday following the first Monday, 2 to 8 November every two even numbered years.
Election Days can only occur from November 2nd through 8th inclusive.
"""
rules = [
Holiday("Election Day",month=11, day=2, offset=pd.DateOffset(weekday=TU(1))),
]使用
start_date = '20160108'
end_date = '20261231'转成功能
def holidays_between_dates(calendar, start_date, end_date):
cal = calendar
dates = cal.holidays(start_date, end_date, return_name=True)
return dates返回
2016-11-08 Election Day
2017-11-07 Election Day
2018-11-06 Election Day
2019-11-05 Election Day
2020-11-03 Election Day
2021-11-02 Election Day
2022-11-08 Election Day
2023-11-07 Election Day
2024-11-05 Election Day
2025-11-04 Election Day
2026-11-03 Election Day除了奇数年,一切都很好。我已经尝试合并了两个偏移,在这个问题中已经讨论过了。在规则中增加2年的抵消
Holiday("Election Day", month=11, day=2, offset=[ pd.DateOffset(weekday=TU(1)), pd.DateOffset(years=2) ])只需将第一次发生的事情移到未来2年。我不确定期望的时间序列是否可能。因此,关于这个问题:
是否可以直接构造这个日历,或者我是否需要用第二个函数从Pandas日历对象中删除奇数年份?
发布于 2016-01-10 19:36:53
你可以在放假时使用纪念而不是抵消,并让它在奇数年内不返回:
def election_observance(dt):
if dt.year % 2 == 1:
return None
else:
return dt + pd.DateOffset(weekday=TU(1))
class USElectionCalendar(AbstractHolidayCalendar):
"""
Federal Presidential and Congressional election day.
Tuesday following the first Monday, 2 to 8 November every two even numbered years.
Election Days can only occur from November 2nd through 8th inclusive.
"""
rules = [
Holiday('Election Day', month=11, day=2, observance=election_observance)
]
cal = USElectionCalendar()
start_date = '20160108'
end_date = '20261231'
print cal.holidays(start_date, end_date, return_name=True)输出:
2016-11-08 Election Day
2018-11-06 Election Day
2020-11-03 Election Day
2022-11-08 Election Day
2024-11-05 Election Day
2026-11-03 Election Day
dtype: object请注意,在构建假日时,您不希望同时使用偏移量和纪念值,这样做会在最近的熊猫版本中引发一个例外。
https://stackoverflow.com/questions/34708626
复制相似问题