You need to enable JavaScript to run this app. Pandas:如何将日期列中的多种时间格式拆分到不同DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

Pandas:如何将日期列中的多种时间格式拆分到不同DataFrame

解决方案

核心思路是通过正则表达式匹配Date列的三种不同日期格式,按需拆分到不同DataFrame中,如果需要保留原数据中的.占位记录,可以先通过前向填充给无效记录打分类标签再拆分。

前置预处理

先对Date列做基础清洗,去除两端空白避免匹配误差:

import pandas as pd
import re

# 此处替换为你自己的原始DataFrame读取逻辑
# df = pd.read_csv("your_file.csv")

# 清洗Date列
df['Date'] = df['Date'].astype(str).str.strip()

方案1:仅保留有效格式记录,自动过滤空值、占位符

直接按正则规则筛选即可,na=False参数会自动排除Date列为空的记录:

# 仅4位纯年份的记录
df_year = df[df['Date'].str.match(r'^\d{4}$', na=False)].copy()

# 年份+季度格式的记录
df_quarter = df[df['Date'].str.match(r'^\d{4} Q[1-4]$', na=False)].copy()

# 年份+月份缩写格式的记录
df_month = df[df['Date'].str.match(r'^\d{4} (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)$', na=False)].copy()

方案2:保留.占位记录,按所属类别归类

如果需要把连续跟随在某类有效记录后的.归属到对应分类,可以先打分类标签再拆分:

# 给有效日期记录打分类标签
def classify_date(date_str):
    if re.match(r'^\d{4}$', date_str):
        return 'year'
    elif re.match(r'^\d{4} Q[1-4]$', date_str):
        return 'quarter'
    elif re.match(r'^\d{4} (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)$', date_str):
        return 'month'
    return None

df['date_type'] = df['Date'].apply(classify_date)
# 前向填充标签,把后续的.和空值归属到最近的有效分类下
df['date_type'] = df['date_type'].ffill()

# 拆分得到三个DataFrame
df1 = df[df['date_type'] == 'year'][['Date', 'Value']].reset_index(drop=True)
df2 = df[df['date_type'] == 'quarter'][['Date', 'Value']].reset_index(drop=True)
df3 = df[df['date_type'] == 'month'][['Date', 'Value']].reset_index(drop=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 13:36:04