You need to enable JavaScript to run this app. 如何读取行长度不均的CSV文件并修复异常行、避免丢失有效数据
优惠活动
大模型
产品
解决方案
定价
更多

如何读取行长度不均的CSV文件并修复异常行、避免丢失有效数据

异常结构CSV文件的读取与修复方案

问题背景

  • 使用pd.read_csv读取目标CSV文件时,默认参数触发解析错误,提示内容为:

    ParserError: Expected 39 fields inline 301474, saw 41

  • 添加error_bad_lines=False参数跳过错误行后程序可正常运行,但会直接丢弃2行包含有效信息的异常行,无法满足数据完整性要求。
  • 触发报错的基础读取代码:
import numpy as np
import pandas as pd
import pickle
import csv

my_udn_f = "20200914181913_18511.csv"
df = pd.read_csv(my_udn_f, sep=',', engine="python")
  • 临时跳过错误行的实现代码:
import numpy as np
import pandas as pd
import pickle
import csv

my_udn_f = "20200914181913_18511.csv"
df = pd.read_csv(my_udn_f, sep=',', engine="python", error_bad_lines=False)

该版本运行时会输出跳过提示:

Skipping line 301474: Expected 39 fields in line 301474, saw 41
Skipping line 313425: Expected 39 fields in line 313425, saw 41

可实现不丢行的修复路径

  • 逐行校验并自适应修复异常行结构
    异常行仅比标准行多2个字段,通常是文本字段内存在未转义的逗号,可通过自定义逐行读取逻辑,将错位的多余字段拼接回对应文本列,无需丢弃数据:
# 读取表头获取标准列数
with open(my_udn_f, 'r', encoding='utf-8') as f:
    csv_reader = csv.reader(f)
    header = next(csv_reader)
    standard_cols = len(header)

cleaned_data = [header]
malformed_line_records = []

with open(my_udn_f, 'r', encoding='utf-8') as f:
    csv_reader = csv.reader(f)
    next(csv_reader) # 跳过重复读取的表头
    for row_idx, row in enumerate(csv_reader, start=2): # 行号从表头下一行开始计数
        if len(row) == standard_cols:
            cleaned_data.append(row)
        else:
            malformed_line_records.append((row_idx, row))
            # 针对多2个字段的场景,将多余内容拼接至最后一个文本列,对齐标准长度
            fixed_row = row[:standard_cols-1] + [','.join(row[standard_cols-1:])]
            cleaned_data.append(fixed_row)

# 生成最终DataFrame
df = pd.DataFrame(cleaned_data[1:], columns=cleaned_data[0])
  • 调整解析参数适配未规范转义的源文件
    大部分字段数不匹配的问题,是因为文本字段内的逗号未被双引号包裹,可补充解析规则,让解析器正确识别字段边界:
df = pd.read_csv(
    my_udn_f,
    sep=',',
    engine="python",
    quotechar='"',
    doublequote=True,
    escapechar='\\',
    on_bad_lines='warn' # 替代旧版error_bad_lines=False,仅输出异常提示不丢弃数据
)
  • 精准定位异常行的错位原因
    可单独提取两行报错的内容,逐字段对比列宽,确认多余字段是来自未闭合的引号、文本内嵌逗号还是行内换行,再针对性修复源文件:
target_error_lines = [301474, 313425]
with open(my_udn_f, 'r', encoding='utf-8') as f:
    for line_num, line_content in enumerate(f, start=1):
        if line_num in target_error_lines:
            print(f"第{line_num}行原始内容:{line_content.strip()}")
            print(f"该行按逗号拆分的字段数:{len(line_content.split(','))}")

内容的提问来源于stack exchange,提问作者Geoffrey Duncan Opiyo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 07:57:00