【问题标题】:Pandas Holiday Calendar Rule for US Election day美国大选日的熊猫假期日历规则
【发布时间】:2016-01-10 17:36:49
【问题描述】:

在使用 Pandas Holiday 类创建假期日历时,我无法确定为美国选举日创建日历的正确规则。美国选举日定义为 11 月第一个星期一之后的星期二,每偶数年举行一次。使用定义的 Holiday 类:

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

一切都很好,除了奇数年份。我已经尝试合并两个偏移量,如issue 中所述。为规则添加 2 年的偏移量

Holiday("Election Day", month=11, day=2, offset=[ pd.DateOffset(weekday=TU(1)), pd.DateOffset(years=2) ])

只需将第一个事件移到未来 2 年。我不确定所需的时间序列是否可行。那么问题来了:

是否可以直接构建这个日历,还是需要使用第二个函数从 Pandas 日历对象中删除奇数年份?

【问题讨论】:

    标签: python pandas calendar


    【解决方案1】:

    您可以在制作假期时使用遵守而不是偏移,并让它在奇数年返回 None:

    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
    

    请注意,您不想在构建 Holiday 时同时使用偏移量和遵守量,并且尝试这样做会在更新的 pandas 版本中引发异常。

    【讨论】:

    • 太棒了!感谢您对使用遵守功能的解释 - 并举例说明。
    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2018-05-01
    • 2012-09-13
    相关资源
    最近更新 更多