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

高性能修改时间序列DataFrame:特定月日的Type列批量调整

高效处理大型时间序列DataFrame的日期匹配与Type列更新

问题概述

给定一个大型时间序列DataFrame(示例数据如下),需要完成:

Name     | date       | value | Type
player 1 | 2010/02/10 | 100   | 2
player 2 | 2011/16/15 | 200   | 3
player 3 | 2012/02/10 | 150   | 4 
player 4 | 2013/11/16 | 136   | 5
player 5 | 2014/02/10 | 94    | 6
  • 定位所有月日为02/10的行,将其Type改为指定值(示例中为2)
  • 若该日期是周末,则改为更新其下一个工作日对应行的Type
  • 数据集规模极大,必须避免循环遍历这类低性能操作

矢量化实现方案(无循环,高性能)

基于Pandas的内置时间处理能力,全程矢量化操作,适合超大数据量:

import pandas as pd
from pandas.tseries.offsets import BDay

# 1. 确保date列是datetime类型(注意示例日期格式是年/日/月,按需调整format参数)
df['date'] = pd.to_datetime(df['date'], format='%Y/%d/%m')

# 2. 筛选出所有2月10日的日期
target_mask = (df['date'].dt.month == 2) & (df['date'].dt.day == 10)

# 3. 对筛选出的日期,计算调整后的目标日期:工作日保留原日期,周末取下一个工作日
adjusted_dates = df.loc[target_mask, 'date'].apply(
    lambda x: x if x.weekday() < 5 else x + BDay(1)
)

# 4. 批量更新Type列到指定值
SPECIFIED_TYPE = 2
df.loc[df['date'].isin(adjusted_dates), 'Type'] = SPECIFIED_TYPE

关键细节说明

  • 矢量化筛选:用dt.month和dt.day直接提取日期部分,生成布尔掩码,效率远高于循环判断
  • 工作日调整:BDay是Pandas内置的工作日偏移工具,自动跳过周末;如果需要支持自定义节假日,可以传入holidays参数扩展
  • 批量更新:最后用isin匹配调整后的日期,一次性完成所有符合条件行的Type列更新,全程无逐行操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:00:28