Sub topic 12
Fixing encoding errors and bad lines
This chapter assumes you can already call pd.read_csv with its basic arguments and that you know what a DataFrame is. Two things often break a load. The bytes in the file may not match the text encoding pandas expects, or some rows may not have the number of fields the header promises. Both failures are fixable at load time, and this chapter covers how to do that and how to avoid hiding real data problems while you do.
What an encoding is and why it fails
A CSV file is a sequence of bytes. An encoding is the rule that maps those bytes to characters. By default read_csv decodes bytes as UTF-8. If the file was saved in another encoding, such as Latin-1 or Windows-1252, some byte sequences are not valid UTF-8, and pandas raises UnicodeDecodeError.
The usual cause is a non-ASCII character such as é, ü or €. ASCII characters are the same in nearly every encoding, so a file with only English letters and digits loads either way.
import pandas as pd
from io import BytesIO
raw = "name,city\nJosé,Málaga\n".encode("latin-1")
try:
pd.read_csv(BytesIO(raw))
except UnicodeDecodeError as err:
print(type(err).__name__)
df = pd.read_csv(BytesIO(raw), encoding="latin-1")
print(df)In Latin-1, é is the single byte 0xE9. UTF-8 reads that byte as the start of a multi-byte sequence, finds the next byte does not fit, and fails. Passing encoding="latin-1" tells pandas to use the right rule.
Choosing the right encoding
The error message shows the offending byte and its position, but it does not name the correct encoding. You have to find it. These are the common candidates:
| Encoding | Typical source |
|---|---|
| `utf-8` | Most modern tools, the pandas default |
| `utf-8-sig` | UTF-8 with a byte order mark, often written by Excel's "CSV UTF-8" export |
| `cp1252` | Windows applications in Western Europe and the Americas |
| `latin-1` | Older Unix and web data, also called `iso-8859-1` |
| `utf-16` | Some Windows exports, often tab-separated |
| `cp932`, `gbk`, `big5` | Legacy Japanese and Chinese files |
Ask whoever produced the file, or check the export settings of the tool that wrote it. If that is not possible, a detection library such as charset-normalizer or chardet can inspect a sample of bytes and return a guess with a confidence score. Treat the guess as a hypothesis and look at the loaded text before you trust it.
Latin-1 never fails, which is the problem
Latin-1 maps every possible byte to some character, so encoding="latin-1" never raises a decoding error. That makes it a tempting fix, but it can silently produce wrong text. A UTF-8 file read as Latin-1 turns é into é. After any encoding change, print a few rows that contain accented or special characters and read them.
cp1252 differs from Latin-1 in the range 0x80 to 0x9F, where it has characters such as € and curly quotes. If a Windows-origin file shows odd control characters, try cp1252.
Byte order marks
A byte order mark (BOM) is a few bytes at the start of a file that some programs add to label the encoding. In UTF-8 it is EF BB BF. If the first column name appears as \ufeffid instead of id, the BOM was not stripped. Read the file with encoding="utf-8-sig", which removes it.
import pandas as pd
from io import BytesIO
raw = "id,name\n1,Ana\n".encode("utf-8-sig")
df = pd.read_csv(BytesIO(raw), encoding="utf-8-sig")
print(list(df.columns))Tolerating a few bad bytes
Sometimes a file is mostly valid UTF-8 with a handful of corrupt bytes. The encoding_errors argument (pandas 1.3 and later) controls what happens when decoding fails:
"strict"is the default and raises an error."replace"substitutes the replacement character�for each bad byte."ignore"drops the bad bytes.
import pandas as pd
from io import BytesIO
raw = b"name,note\nAna,caf\xe9 au lait\n"
df = pd.read_csv(BytesIO(raw), encoding="utf-8", encoding_errors="replace")
print(df["note"].iloc[0])Prefer "replace" over "ignore". A visible � tells you data was damaged, while "ignore" removes the evidence and can merge neighbouring characters into a different word.
Bad lines
A bad line is a row whose number of fields does not fit the table. The most common case is a row with more fields than the header, caused by an unquoted comma inside a value such as Smith, John.
import pandas as pd
from io import StringIO
text = "id,name\n1,Ana\n2,Ben,extra\n3,Cy\n"
try:
pd.read_csv(StringIO(text))
except pd.errors.ParserError as err:
print(err)The default message reads like Error tokenizing data. C error: Expected 2 fields in line 3, saw 3. Line numbers count from 1 and include the header, so line 3 is the row beginning 2,Ben. Open the file at that line first. The file itself is usually the problem, not the pandas call.
Two edge cases are worth knowing:
- A row with too few fields is not an error. pandas fills the missing trailing fields with
NaN. - If every data row has one more field than the header, pandas treats the extra leading field as the index instead of raising an error. If your columns look shifted, check that the header is not missing a name.
The on_bad_lines argument
on_bad_lines (pandas 1.3 and later, replacing the older error_bad_lines and warn_bad_lines) sets what happens to bad rows:
| Value | Behavior |
|---|---|
| `"error"` | Raise `ParserError` (default) |
| `"warn"` | Print a warning to stderr and drop the row |
| `"skip"` | Drop the row silently |
| A function | Call it with the row's fields and use what it returns (needs `engine="python"`, pandas 1.4 and later) |
import pandas as pd
from io import StringIO
text = "id,name\n1,Ana\n2,Ben,extra\n3,Cy\n"
skipped = pd.read_csv(StringIO(text), on_bad_lines="skip")
print(len(skipped))This returns two rows, ids 1 and 3.
Collecting or repairing bad rows with a function
Dropping rows without knowing what was lost is risky. A callable receives the fields of the bad row as a list of strings. It can return a fixed list of fields to keep the row, or None to drop it. Because the callable can also record the row, you can see exactly what was discarded.
import pandas as pd
from io import StringIO
text = "id,name\n1,Ana\n2,Ben,extra\n3,Cy\n"
rejected = []
def handle(fields):
rejected.append(fields)
return None
df = pd.read_csv(StringIO(text), engine="python", on_bad_lines=handle)
print(len(df))
print(rejected)
repaired = pd.read_csv(
StringIO(text),
engine="python",
on_bad_lines=lambda fields: fields[:2],
)
print(repaired)The first read keeps ids 1 and 3 and prints [['2', 'Ben', 'extra']] for the rejected list. The second read truncates the bad row to its first two fields, so all three rows survive. The Python engine is slower than the default C engine, so use it for repair on files of moderate size or on a file you have already filtered.
Quotes that swallow lines
A stray quote character can make the parser treat everything up to the next quote as one field, which hides many lines inside a single value. The symptoms are a row count far below the line count of the file, or an error about EOF inside a string. If the file does not use quoting at all, turn it off:
import csv
import pandas as pd
df = pd.read_csv("notes.csv", quoting=csv.QUOTE_NONE)Only do this when no field legitimately contains the separator. Otherwise fix the source file.
A decision path
Common mistakes
- Using
encoding="latin-1"on a file that was UTF-8, producing text such aséwithout any error. - Using
on_bad_lines="skip"and never counting how many rows were lost. Compare the row count with the line count of the file, or use a callable that records rejects. - Setting
encodingon a file object that is already open in text mode. The file's own encoding was fixed when it was opened. Pass the path or open the file withopen(path, encoding=...). - Using the old
error_bad_lines=False. It was removed in pandas 2.0, so useon_bad_lines.
Exercise
A file loads with read_csv(path) without errors, but the first column is named \ufeffid and a lookup df["id"] raises KeyError. What caused this, and what is the fix?
Show answer
The file starts with a UTF-8 byte order mark that was kept as part of the first column name. Read it with encoding="utf-8-sig", which strips the BOM, so the column becomes id.
Exercise
You read a 10,000-line file with on_bad_lines="skip" and get 9,940 rows. Using the options from this chapter, how would you find out which lines were dropped and then decide whether to repair them?
Show answer
Re-read the file with engine="python" and a callable for on_bad_lines that appends each row's fields to a list and returns None. The list then holds the 60 rejected rows. Inspect them, and if they share a pattern, such as an unquoted comma in one column, return a repaired list of fields from the callable instead of None, or fix the source file.