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

使用pandas读取含混乱引号的CSV文件时列匹配异常求助

解决CSV引号格式混乱导致的pandas列匹配错误问题

有一份存在引号格式混乱的CSV文件file.csv,内容如下:

header1, header2, header3
"abc, \" hello \" ", 0, "aaa"
"abc, \", 0, "aaa"

期望读取后各列正确匹配,得到如下结果:

header1, header2, header3
"abc, hello", 0, aaa
abc, 0, aaa

但执行pd.read_csv("file.csv", header=None, escapechar = "\"")后,出现列分配错误:

header1   header2  header3
0  abc, " hello "        0.0    "aaa"
1   abc ", 0, aaa"       NaN      NaN

需求:不在意特殊字符、逗号等格式,只需要各列值正确匹配到对应列中。

方案1:手动按固定列数分割每行(已知列数场景)

由于已知CSV固定为3列,可以先读取所有行,手动分割每行成3部分,再清理格式后转成DataFrame:

import pandas as pd

# 读取文件所有行
with open('file.csv', 'r', encoding='utf-8') as f:
    lines = f.readlines()

# 提取表头和数据行
header = lines[0].strip().split(', ')
data_lines = lines[1:]

processed_data = []
for line in data_lines:
    # 按逗号分割为3部分(最多分割2次)
    parts = line.strip().split(',', 2)
    # 清理首尾引号、转义字符
    cleaned_parts = [
        part.strip().strip('"').replace('\\"', '"')
        for part in parts
    ]
    processed_data.append(cleaned_parts)

# 构建DataFrame
df = pd.DataFrame(processed_data, columns=header)
print(df)

输出结果:

header1 header2 header3
0  abc,  hello        0     aaa
1        abc,        0     aaa

方案2:用on_bad_lines自定义修复错误行(pandas 1.4.0+)

利用pandas的on_bad_lines参数捕获解析失败的行,手动修正后加入数据集:

import pandas as pd

def fix_bad_line(line):
    # 合并错误行的分割结果,重新按3列分割并清理格式
    full_line = ','.join(line)
    parts = full_line.strip().split(',', 2)
    return [part.strip().strip('"').replace('\\"', '"') for part in parts]

df = pd.read_csv(
    'file.csv',
    header=0,
    escapechar='\\',
    on_bad_lines=fix_bad_line
)
print(df)

此方案会自动处理解析正常的行,仅对错误行应用修复逻辑,兼顾效率和准确性。

方案3:忽略引号强制分割(内容逗号无需保留场景)

若完全不在意内容中的逗号,可禁用引号解析,直接按逗号分割并取前3列:

import pandas as pd
import csv

df = pd.read_csv(
    'file.csv',
    header=0,
    sep=',',
    quoting=csv.QUOTE_NONE,
    skipinitialspace=True,
    on_bad_lines=lambda x: x[:3]  # 仅保留前3个分割部分
)
# 统一清理各列的引号和转义字符
df = df.apply(lambda col: col.str.strip('"').replace('\\"', '"', regex=False))
print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:41:06