You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从节假日字典提取指定日期,给DataFrame的business_days列加0.5?

解决方案

步骤1:定义节假日白名单

把你给出的第一份节假日列表转成集合,方便快速判断是否属于排除项:

WHITELIST_HOLIDAYS = {
    "New Year's Day",
    'Martin Luther King Jr. Day',
    'Memorial Day',
    'Independence Day',
    'Labor Day',
    'Thanksgiving',
    'Christmas Day',
    "New Year's Day (Observed)",
    'Martin Luther King Jr. Day (Observed)',
    'Memorial Day (Observed)',
    'Independence Day (Observed)',
    'Labor Day (Observed)',
    'Thanksgiving (Observed)',
    'Christmas Day (Observed)'
}

步骤2:提取需要处理的节假日日期

从你的DataFrame中自动获取所有涉及的年份,覆盖历史数据,再遍历这些年份筛选出不在白名单里的节假日日期:

import holidays
import pandas as pd

# 确保DataFrame的日期列是datetime类型(否则无法和holidays返回的日期匹配)
df['PredictionTargetDateEOM'] = pd.to_datetime(df['PredictionTargetDateEOM'])

# 获取DataFrame覆盖的所有年份范围
min_year = df['PredictionTargetDateEOM'].dt.year.min()
max_year = df['PredictionTargetDateEOM'].dt.year.max()

# 收集需要加0.5的节假日日期
target_holiday_dates = set()
for year in range(min_year, max_year + 1):
    # holidays.US返回的是{datetime: 节假日名称}的字典,遍历键值对
    for date, holiday_name in holidays.US(years=year).items():
        if holiday_name not in WHITELIST_HOLIDAYS:
            target_holiday_dates.add(date)

步骤3:更新DataFrame的business_days列

用isin()匹配日期,直接对符合条件的行进行数值更新:

# 匹配目标日期,给对应行的business_days加0.5
df.loc[df['PredictionTargetDateEOM'].isin(target_holiday_dates), 'business_days'] += 0.5

关键细节

  1. 类型一致性:必须把DataFrame的日期列转成datetime类型,否则无法和holidays.US返回的datetime键正确匹配
  2. 自动适配年份:通过提取DataFrame的最小/最大年份,不用手动指定年份范围,完美适配历史数据
  3. 效率优化:用集合存储白名单和目标日期,比列表的in操作快很多,适合处理大数量级的DataFrame(比如你的17万行数据)

内容的提问来源于stack exchange,提问作者Hefe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 14:06:20