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

Python转换年月数据为日期格式时遇ValueError报错求助

问题与解决方案

问题重现

执行以下代码将年月数据转换为YYYY-MM格式时抛出错误:

dateformat['date'] = pd.to_datetime(dateformat['year_month'], format='%Y%m')

待转换的year_month数据片段:

array(['20071', '20072', '20073', ..., '202019', ..., '20228'], dtype=object)

错误信息:

ValueError: unconverted data remains: 9

错误原因

  1. 格式不匹配:%Y%m要求输入为「4位年份+2位月份」,但你的数据中1-9月仅用1位数字表示(如20071对应2007年1月),格式规则无法匹配;
  2. 存在脏数据:数据中包含无效值202019——月份取值范围为1-12,该值的月份部分为19,属于非法数据,直接触发格式转换失败的报错。

解决方案

步骤1:清理脏数据

先筛选或修正非法数据:

# 方法1:筛选符合规则的有效数据(4位年+1-2位合法月份)
valid_mask = dateformat['year_month'].str.match(r'^\d{4}(0?[1-9]|1[012])$')
dateformat = dateformat[valid_mask]

# 方法2:手动修正已知错误值(如将202019改为202009)
dateformat.loc[dateformat['year_month'] == '202019', 'year_month'] = '202009'

步骤2:统一格式并转换

将1位月份补为2位,再执行日期转换:

# 给1位月份补零,统一为6位的「YYYYMM」格式
dateformat['year_month_fixed'] = dateformat['year_month'].str.pad(width=6, side='right', fillchar='0')

# 转换为datetime类型
dateformat['date'] = pd.to_datetime(dateformat['year_month_fixed'], format='%Y%m')

# 若需要字符串格式的YYYY-MM,可进一步处理
dateformat['date_str'] = dateformat['date'].dt.strftime('%Y-%m')

简化方案(自动识别格式)

如果数据量不大,可省略手动补零步骤,让pandas自动识别格式(需先清理脏数据):

# 自动识别格式,转换失败的行设为NaT
dateformat['date'] = pd.to_datetime(dateformat['year_month'], errors='coerce')

# 过滤转换失败的行
dateformat = dateformat.dropna(subset=['date'])

# 转为YYYY-MM字符串
dateformat['date_str'] = dateformat['date'].dt.strftime('%Y-%m')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:55:30