如何使用pandas与Jupyter Notebook定位CSV文件的日期格式错误
解决方案
首先调整日期转换代码,添加errors='coerce'参数,将不符合格式的日期值强制转换为时间类型空值NaT,不会直接抛出错误中断执行:
pf['create_time'] = pd.to_datetime(pf['create_time'], format="%d/%m/%Y", errors='coerce')
之后直接筛选create_time为空的行,就是所有格式异常的记录:
# 提取所有错误行 error_rows = pf[pf['create_time'].isna()] # 打印错误行的原始create_time值和对应行号 print(error_rows[['create_time']]) # 可以导出错误行到单独CSV文件方便排查 error_rows.to_csv('create_time_error_records.csv', encoding='utf-8-sig', index_label='原始行号')
如果需要对照原始值排查,可以提前备份原始create_time字段:
# 备份原始字段 pf['create_time_raw'] = pf['create_time'].copy() # 执行转换 pf['create_time'] = pd.to_datetime(pf['create_time'], format="%d/%m/%Y", errors='coerce') # 查看错误行的完整关联信息 error_detail = pf[pf['create_time'].isna()][['owner_id', 'create_time_raw', 'active_time']] print(error_detail)
你遇到的
#VALOR!是Excel公式计算错误的标记,大概率是CSV导出时部分行的create_time字段公式计算失败遗留的异常值,以上方法可以一次性捞出所有错误行,无需在Excel中逐行检索。
内容的提问来源于stack exchange,提问作者Rodrigo Venturi
相关产品推荐
相关产品推荐

