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

如何使用Pandas跳过数据集中字段数不足的行?

解决pandas读取CSV时仅保留字段数与列数匹配的行

on_bad_lines='skip'只能跳过字段数多于列数的行,字段数不足的行仍会触发报错。要实现仅保留字段数与列数完全匹配的行,可以通过自定义on_bad_lines处理函数来实现:

  1. 先读取CSV表头,确定预期的列数
  2. 定义过滤函数,跳过所有字段数不等于预期列数的行

具体代码如下:

import pandas as pd

# 读取表头获取预期列数
with open('your_dataset.csv', 'r', encoding='unicode_escape') as f:
    header_line = f.readline().strip()
    expected_column_count = len(header_line.split(','))

# 自定义坏行处理函数:仅保留字段数匹配的行
def filter_mismatched_lines(fields):
    if len(fields) != expected_column_count:
        return None  # 返回None表示跳过该行
    return fields

# 读取CSV并应用过滤规则
df = pd.read_csv(
    'your_dataset.csv',
    sep=',',
    encoding='unicode_escape',
    on_bad_lines=filter_mismatched_lines
)

这个方法会同时过滤掉字段数过多和过少的行,最终得到仅包含字段数与列数匹配的行的DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:55:25