You need to enable JavaScript to run this app. Python Pandas解析列数不匹配的竖线分隔CSV报Tokenize错误,如何拆分得到目标DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas解析列数不匹配的竖线分隔CSV报Tokenize错误,如何拆分得到目标DataFrame

混合列数竖线分隔CSV拆分实现方案

问题根因

默认调用pd.read_csv时,内置解析器会对列数做严格一致性校验,文件内同时存在8字段B类行、10字段T类行的结构会直接触发tokenize解析错误,无法一次性读入。

实现方案

采用逐行分流逻辑,先按行首标识把两类行拆分到独立存储列表,再分别构建DataFrame,完全规避解析器的列数校验限制。

核心实现代码

import pandas as pd

b_row_store = []
t_row_store = []

# 逐行读取原始文件
with open('input.csv', 'r', encoding='utf-8') as f:
    for raw_line in f:
        # 清理行首尾的换行、空白字符,跳过空行
        cleaned_line = raw_line.strip()
        if not cleaned_line:
            continue
        # 按行首标识分流
        if cleaned_line.startswith('B'):
            # 拆分字段,过滤B类行末尾尾随分隔符产生的空字符串
            parsed_b = [field for field in cleaned_line.split('|') if field != '']
            b_row_store.append(parsed_b)
        elif cleaned_line.startswith('T'):
            parsed_t = cleaned_line.split('|')
            t_row_store.append(parsed_t)

# 生成两个独立的DataFrame
df_b = pd.DataFrame(b_row_store)
df_t = pd.DataFrame(t_row_store)

原始行格式适配

如果需要完全保留原始行的竖线连接格式,不需要拆分出独立字段列,可直接存储原始行文本:

# 保留原始行格式的实现逻辑
b_raw_store = []
t_raw_store = []
with open('input.csv', 'r', encoding='utf-8') as f:
    for raw_line in f:
        cleaned_line = raw_line.strip()
        if not cleaned_line:
            continue
        if cleaned_line.startswith('B'):
            b_raw_store.append([cleaned_line])
        elif cleaned_line.startswith('T'):
            t_raw_store.append([cleaned_line])

df_b_raw = pd.DataFrame(b_raw_store, columns=['原始行内容'])
df_t_raw = pd.DataFrame(t_raw_store, columns=['原始行内容'])

关键注意点

  • B类行末尾自带一个尾随竖线,拆分后会产生末尾空字段,通过列表推导过滤空值,可保证B类行拆分后和预期的有效字段数量完全匹配
  • 若尝试用宽松模式直接读取整个文件,需设置engine='python'、on_bad_lines='skip'参数,但该模式会统一按最大列数填充DataFrame宽度,B类行缺失的2列会被填充为NaN,无法完全匹配独立列结构的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 08:06:01