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

在pandas未指定格式时,将字符串序列转为datetime如何排除特定格式?

如何在pandas.to_datetime中排除特定日期格式(不指定目标格式)

pandas的pd.to_datetime本身并没有内置的excluded_formats参数来直接排除特定格式,但可以通过手动筛选的方式实现需求——先识别出符合要排除格式的字符串,只对剩余内容进行自动日期推断。

具体实现步骤

  • 定义要排除的日期格式列表;
  • 编写判断函数,检查字符串是否匹配任意一种排除格式;
  • 对未匹配排除格式的字符串,使用pd.to_datetime自动推断解析。

示例代码

import pandas as pd
from datetime import datetime

# 示例数据
df = pd.DataFrame({'dates': ['21-5-2018', '2/4/2000', '05-21-2018']})

# 定义需要排除的日期格式
excluded_formats = ['%m-%d-%Y', '%m %Y']

# 判断字符串是否匹配排除格式的函数
def matches_excluded_format(date_str):
    for fmt in excluded_formats:
        try:
            datetime.strptime(date_str, fmt)
            return True
        except ValueError:
            continue
    return False

# 解析日期:排除指定格式的内容,其余自动推断
df['parsed_dates'] = df['dates'].apply(
    lambda x: pd.NaT if matches_excluded_format(x) else pd.to_datetime(x, errors='coerce')
)

print(df)

代码说明

  • 函数matches_excluded_format通过datetime.strptime尝试匹配排除格式,匹配成功则标记为需要排除;
  • 使用apply和匿名函数,对排除的行赋值pd.NaT(也可根据需求保留原字符串),未排除的行调用pd.to_datetime自动推断格式;
  • errors='coerce'确保无法自动推断的行也会被转为NaT,避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:48:30