skip to content

In pandas, read_csv on a clickstream file fails with 'Expected 6 fields in line 48213, saw 7': what do the on_bad_lines options do, and which would you choose?

level: seniorimportance: should knowfreq 45%

answer

  1. too many fields, not too few
  2. error, warn, skip
  3. a function needs another engine
  4. find why the line has an extra field

basics

~10 s

on_bad_lines decides what happens to lines with too many fields: 'error' (default) raises ParserError, 'warn' drops each with a ParserWarning, 'skip' drops silently, and a callable works only with engine='python' or 'pyarrow'.

solid answer

~40 s

A bad line, for `read_csv`, is one with **more** fields than the header. The default `on_bad_lines='error'` raises `ParserError` (the C engine's message reads `Error tokenizing data. C error: Expected 6 fields in line 48213, saw 7`). `'warn'` drops each such line and emits a `ParserWarning` like `Skipping line 48213: expected 6 fields, saw 7`; `'skip'` drops them without a word. A callable can repair or log the line, but only with `engine='python'` or `engine='pyarrow'`; with the default engine it raises `ValueError`. Lines with **fewer** fields are not bad: their trailing fields are filled with NaN. In a pipeline I use `'warn'` and count the warnings, then fix the cause, usually an unquoted comma inside a URL or user-agent field.

code

python · 28 lines
python
import io
import warnings

import pandas as pd

raw = "user_id,page,ms\nu1,/home,120\nu2,/search?q=a,b,340\nu3,/cart\n"

try:
    pd.read_csv(io.StringIO(raw))
except pd.errors.ParserError as exc:
    print(type(exc).__name__)  # ParserError (line 3 has 4 fields)

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    df = pd.read_csv(io.StringIO(raw), on_bad_lines="warn")
print(len(df), len(caught))  # 2 1  (u2 dropped, one ParserWarning)
print(df["user_id"].tolist())  # ['u1', 'u3']  u3 kept, its ms is NaN

rejected = []


def log_and_drop(fields):
    rejected.append(fields)
    return None


pd.read_csv(io.StringIO(raw), on_bad_lines=log_and_drop, engine="python")
print(rejected)  # [['u2', '/search?q=a', 'b', '340']]

go deeper

for a junior

Recall that a line with too many fields makes read_csv raise by default, and that on_bad_lines has error, warn and skip.

for a middle

Explain the difference between long and short lines, the warning text, and why a callable needs the python or pyarrow engine.

for a senior

Diagnose the extra field from the line number, prefer warn with counted warnings over skip, and fix quoting at the producer when you can.

for a principal

Decide which feeds may drop malformed records at all, and require a dropped-line count in every ingestion report that allows it.

## What counts as a bad line `read_csv` learns the expected number of fields from the header (or from `names`). A data line with **more** fields than that cannot be placed into the columns, and pandas calls it a **bad line**. A line with **fewer** fields is treated differently: the user guide states that the trailing fields are filled with NA values. So the reader can silently accept a short, truncated record while refusing a long one. The usual cause of an extra field in a clickstream export is a delimiter inside a value that was not quoted: a URL with a comma in its query string, or a user-agent string. One unquoted comma shifts every later field one column to the right. ## The four choices | `on_bad_lines` | What happens to a line with too many fields | |---|---| | `'error'` (default) | `ParserError` is raised and nothing is returned | | `'warn'` | the line is dropped and a `ParserWarning` names it | | `'skip'` | the line is dropped silently | | a callable | your function decides; needs `engine='python'` or `engine='pyarrow'` | Details behind the table: - **The error message** from the C engine has the form `Error tokenizing data. C error: Expected 6 fields in line 48213, saw 7`. The line number counts lines of the file from 1, header included, so it points straight at the record to inspect. - **The C engine's warning text** is `Skipping line 48213: expected 6 fields, saw 7`, raised as `pandas.errors.ParserWarning` (the Python and PyArrow engines word it differently but use the same class). A test or a job can capture these with the `warnings` module and count them. - **A callable with `engine='python'`** receives the bad line as a list of strings split on `sep`. Returning `None` drops the line; returning a list keeps it, and if that list still has too many elements pandas emits a `ParserWarning` and drops the extras. The user guide adds that the callable handles only lines with too many fields; lines that fail for other reasons are silently skipped. - **A callable with `engine='pyarrow'`** follows PyArrow's invalid-row handler signature instead, so the same function does not work on both engines. - **With the default C engine, a callable raises `ValueError`**, even when you never named an engine. - **`error_bad_lines` and `warn_bad_lines` are gone.** They were deprecated in pandas 1.3 in favour of `on_bad_lines` and removed in 2.0. ## Where the extra field comes from A file written by pandas itself rarely has this problem: `to_csv` uses `csv.QUOTE_MINIMAL` by default, which quotes any field containing the separator, the quote character or a line break, and `read_csv` honours those quotes with its default `quotechar='"'`. Bad lines usually come from a producer that joined strings with commas by hand, or one that quotes but escapes embedded quotes differently. In the second case the reader options `escapechar` and `doublequote` describe the producer's convention and can turn every bad line back into a good one without dropping anything. Read a handful of the reported lines raw before choosing an `on_bad_lines` value. ## Choosing in production `'skip'` is the tempting choice and usually the wrong one: data disappears with no record of how much. A sounder sequence: 1. Run once with the default `'error'` to get the first offending line number, then read that line raw to see why it is long. 2. If the producer can be fixed (quote fields with `quoting`, or switch the delimiter), fix it there. 3. If it cannot, read with `on_bad_lines='warn'`, capture the warnings, and record how many lines were dropped next to the row count, so a jump is visible. 4. If the extra field has a known shape (a comma inside the URL column), repair it with a callable on `engine='python'`, accepting that the Python engine is slower on a 20 GB file. Two alternatives keep every record. Passing `names` with one more column than the header holds lets long lines fit, and shorter lines get NaN in the extra column, so you can find and fix them after the read. And remember the other direction: short lines are filled with NaN without any warning, so check the last columns for unexpected missing values as well. Comparing the input line count with `len(df)` is the general check for silently dropped records; the library-neutral lesson on reads that drop rows covers it.

  • on_bad_lines='skip' made the job pass. What risk did it introduce?
    Silent data loss: every long line disappears with no count and no message, so a producer bug that breaks thousands of lines looks like a quiet day. Use `'warn'`, capture the `ParserWarning`s, and alert when the dropped count crosses a threshold. Also check that short lines, which are filled with NaN rather than dropped, are not hiding the same bug.
  • Can you keep the long lines instead of dropping them?
    Yes. Pass `names` with one more column than the header has (and `header=0` to replace the file's header), so every line fits and short lines get NaN in the extra column. Then find rows where the extra column is filled and repair them. A callable on `engine='python'` can also return a fixed list of fields per bad line.

  • on_bad_lines='skip' also drops lines with too few fields
  • A callable on_bad_lines works with the default C engine
  • on_bad_lines='warn' keeps the bad line and only logs it
  • error_bad_lines=False is how you skip bad lines
  • Lines with missing trailing fields raise ParserError by default