Pandas Business Days & Holidays Guide

Pandas can generate workdays using the pandas.bdate_range() function and generate holidays by customizing the calendar parameters.

Here is an example demonstrating how to use Pandas to generate business days and custom holidays for the year 2021.

import pandas as pd
from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday, USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay, USLaborDay, USThanksgivingDay, USChristmasDay
from pandas.tseries.offsets import CustomBusinessDay

# 自定义节假日日历
class CustomCalendar(AbstractHolidayCalendar):
    rules = [
        Holiday('New Year', month=1, day=1),
        Holiday('Independence Day', month=7, day=4),
        Holiday('Thanksgiving', month=11, day=1, offset=USThanksgivingDay),
        Holiday('Christmas', month=12, day=25)
    ]

# 设置工作日和节假日参数
bday_us = CustomBusinessDay(calendar=CustomCalendar())
holidays = pd.to_datetime(['2021-01-01', '2021-07-04', '2021-11-25', '2021-12-25'])

# 生成2021年的工作日
start_date = '2021-01-01'
end_date = '2021-12-31'
dates = pd.bdate_range(start_date, end_date, freq=bday_us, holidays=holidays)

# 打印结果
print(dates)

In the code above, we defined a CustomCalendar class to represent a custom holiday calendar, which includes some common holidays. Then, we used CustomBusinessDay to create a custom business day frequency, passing the custom holiday calendar as a parameter to it. Finally, we used the pd.bdate_range() function to generate the business days for the year 2021, while specifying the holiday parameter. Lastly, we printed the generated date results.

Note: The above code is based on the United States, adjustments will be needed based on the corresponding holiday calendar when generating workdays and holidays for other regions.

bannerAds