如何覆寫 BDay 函式以識別 Juneteenth?使用pandas-1.4.2
from datetime import date
from pandas.tseries.offsets import BDay
date(2022,6,17) BDay(1)
uj5u.com熱心網友回復:
我們需要告訴熊貓關于假期的事情。BusinessDay不能處理假期,所以我們需要用 替換它CustomBusinessDay,并告訴它我們有哪些假期。
熊貓中包含一些。我將根據您的問題假設美國:
from datetime import date
import pandas.tseries.holiday
holiday_dates = (pandas.tseries.holiday.USFederalHolidayCalendar()
.holidays(start="2022-01-01", end="2023-01-01"))
# holiday_dates output:
# DatetimeIndex(['2022-01-17', '2022-02-21', '2022-05-30', '2022-06-20',
# '2022-07-04', '2022-09-05', '2022-10-10', '2022-11-11',
# '2022-11-24', '2022-12-26'],
# dtype='datetime64[ns]', freq=None)
所以熊貓知道一些假期。
如果你使用 Pandas 1.4 或更高版本,Juneteenth 包含在其中USFederalHolidayCalendar,你應該像這樣直接使用它:
from pandas.tseries.offsets import CustomBusinessDay
date(2022,6,17) CustomBusinessDay(1, holidays=holiday_dates)
# Timestamp('2022-06-21 00:00:00')
對于較舊的 Pandas,我們可以讓它知道假期,如下所示。
Juneteenth 對應于 6 月 19 日,但似乎特別在 2022 年的 6 月 20 日作為假期落下。Pandas 對此有一個規則 - 下一個作業日(如果您更準確地了解規則,請更新此答案)。
這是將其添加為假期的漫長但正確的方法:
import pandas.tseries.holiday
from pandas.tseries.holiday import next_workday
juneteenth = (pandas.tseries.holiday.Holiday("Juneteenth",
month=6, day=19, observance=next_workday))
# Holiday: Juneteenth (month=6, day=19, observance=<function next_workday at 0x7f25db280dc0>)
# Now compute the actual dates the holiday will fall on in 2022
# (can be any date or year range)
juneteenth_dates = juneteenth.dates(date(2022,1,1), date(2023,1,1))
from pandas.tseries.offsets import CustomBusinessDay
# Now compute the offset we wanted
date(2022,6,17) CustomBusinessDay(1, holidays=juneteenth_dates)
# Timestamp('2022-06-21 00:00:00')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496326.html
上一篇:在R中計算會話持續時間
