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

如何用Pandas结合np.where转换DataFrame中日期格式(%d-%m-%y→%y-%m-%d)

日期格式转换的正确实现方法

你的原代码存在两个关键问题:一是np.where的第一个参数需要布尔条件而非元组,二是strptime的格式参数与待解析日期格式不匹配。以下是几种实用的实现方案:

方案1:直接用pandas内置函数(推荐)

如果所有日期都是%d-%m-%y格式,直接用pd.to_datetime解析后再转换为目标格式最简洁:

import pandas as pd

# 假设df已从CSV导入
df['date'] = pd.to_datetime(df['date'], format='%d-%m-%y').dt.strftime('%y-%m-%d')
  • pd.to_datetime(df['date'], format='%d-%m-%y'):将%d-%m-%y格式的字符串解析为datetime对象
  • .dt.strftime('%y-%m-%d'):将datetime对象转换为%y-%m-%d格式的字符串

如果需要保留datetime类型而非字符串,去掉.dt.strftime('%y-%m-%d')即可。

方案2:处理混合格式场景(类似你想要的np.where逻辑)

如果数据中存在多种日期格式,仅转换%d-%m-%y格式的日期,其余保持原样:

import pandas as pd
import numpy as np

# 用正则匹配%d-%m-%y格式的日期(比如"05-08-24")
mask = df['date'].str.match(r'^\d{2}-\d{2}-\d{2}$')

df['date'] = np.where(
    mask,
    pd.to_datetime(df['date'], format='%d-%m-%y').dt.strftime('%y-%m-%d'),
    df['date']
)
  • mask是布尔数组,标记哪些日期需要转换
  • np.where根据mask选择转换后的值或原日期

处理格式错误的情况

如果存在无法解析的日期字符串,可添加errors='coerce'将其转为NaT(缺失值),方便后续处理:

df['date'] = pd.to_datetime(df['date'], format='%d-%m-%y', errors='coerce').dt.strftime('%y-%m-%d')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:02:28