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

如何使用Pandas按星期规则拆分DataFrame日期列

Pandas按星期拆分日期列实现方案

你的原始数据结构为第一列是Hours小时字段,其余列名均为YYYY-MM-DD格式的日期,可直接通过列名转时间判断星期属性完成筛选拆分,全程不需要重构原始数据的行结构。

第一步:移除周末列,生成纯工作日DataFrame

Pandas中datetime对象的weekday()方法返回值规则为:0=周一、1=周二、2=周三、3=周四、4=周五、5=周六、6=周日,直接按返回值过滤列即可:

import pandas as pd

# 替换为你自己的原始DataFrame变量名
raw_df = "替换成你的原始DataFrame"

# 提取所有日期列(排除第一列Hours)
date_columns = [col for col in raw_df.columns if col != "Hours"]
# 将日期格式的列名转为可识别星期的时间对象
date_objs = pd.to_datetime(date_columns)

# 筛选出周一到周五的列(排除返回值为5、6的周六、周日)
workday_columns = [col for col, dt in zip(date_columns, date_objs) if dt.weekday() < 5]
# 拼接Hours列得到工作日DataFrame
workday_df = raw_df[["Hours"] + workday_columns].copy()

第二步:拆分工作日为两个目标DataFrame

基于已经识别好的日期星期属性,直接拆分周五、周一到周四的列即可:

# 筛选所有周五的列(weekday返回值为4)
friday_columns = [col for col, dt in zip(workday_columns, date_objs) if dt.weekday() == 4]
friday_df = raw_df[["Hours"] + friday_columns].copy()

# 筛选周一到周四的列(weekday返回值为0-3)
mon_to_thu_columns = [col for col, dt in zip(workday_columns, date_objs) if dt.weekday() < 4]
mon_to_thu_df = raw_df[["Hours"] + mon_to_thu_columns].copy()

提示:如果列名存在不符合YYYY-MM-DD格式的异常值,可以在pd.to_datetime()中传入errors="coerce"参数,先过滤掉解析为空值的异常列再做后续处理,避免代码报错。

效果参考

举个简单的列名筛选例子,假设原始DataFrame列顺序为:
['Hours', '2024-06-01', '2024-06-02', '2024-06-03', '2024-06-04', '2024-06-05', '2024-06-06', '2024-06-07']
其中2024-06-01是周六、2024-06-02是周日,2024-06-07是周五:

  • workday_df包含列:['Hours', '2024-06-03', '2024-06-04', '2024-06-05', '2024-06-06', '2024-06-07']
  • friday_df包含列:['Hours', '2024-06-07']
  • mon_to_thu_df包含列:['Hours', '2024-06-03', '2024-06-04', '2024-06-05', '2024-06-06']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:36:20