Sub topic 12
Fixing encoding errors and bad lines
This chapter assumes you can call pd.read_csv, you know what a DataFrame is, and you have pandas installed. It covers two failures that appear with files exported from other systems: text that cannot be decoded, and rows that do not match the header.
Why these errors happen
A CSV file is bytes. pandas must turn those bytes into text using an encoding. By default it assumes UTF-8. If the file was saved as Latin-1 or Windows-1252, bytes such as 0xe9 (the letter é) are not valid UTF-8, and pandas raises an error.
A separate problem is structure. If a row has more fields than the header, the parser cannot tell which columns the extra values belong to.
Fixing encoding errors
A decoding failure looks like this:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 12: invalid continuation bytePass the right encoding. The example below writes a Latin-1 file, then reads it back.
import pandas as pd
with open("cities.csv", "w", encoding="latin-1") as f:
f.write("city,country\nZürich,Switzerland\nMálaga,Spain\n")
df = pd.read_csv("cities.csv", encoding="latin-1")
print(df)Common choices are utf-8, utf-8-sig (UTF-8 with a byte order mark, often written by Excel), cp1252 (Windows) and latin-1.
If you do not know the encoding, try cp1252 first for files from Windows tools. Reading a file with the wrong single-byte encoding usually does not raise an error. It produces garbled text such as Zürich, so always check the result.
Handling bad lines
Consider a file where one row has an extra field:
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 error message names the line number and the expected field count, which tells you where to look in the source file.
The on_bad_lines argument controls the behavior:
| Value | Effect |
|---|---|
| `"error"` | Raise `ParserError`. This is the default. |
| `"warn"` | Skip the bad line and print a warning. |
| `"skip"` | Skip the bad line silently. |
import pandas as pd
from io import StringIO
text = "id,name\n1,Ana\n2,Ben,extra\n3,Cy\n"
df = pd.read_csv(StringIO(text), on_bad_lines="warn")
print(df)The output keeps rows 1 and 3. Row 2 is dropped.
The default C parser also accepts a callable for on_bad_lines only with engine="python". The callable receives the split fields of the bad line and returns a repaired list, or None to drop it.
import pandas as pd
from io import StringIO
text = "id,name\n1,Ana\n2,Ben,extra\n3,Cy\n"
df = pd.read_csv(
StringIO(text),
engine="python",
on_bad_lines=lambda fields: fields[:2],
)
print(df)Here the extra field is trimmed and all three rows survive.
Common mistakes
- Using
on_bad_lines="skip"without counting rows afterward. Comparelen(df)with the number of data lines in the file to see how many were lost. - Skipping bad lines when the real cause is an unquoted delimiter inside a value, such as
Smith, John. Fix the quoting or thesepinstead. - Passing
encodingtoread_excel. Excel files are not decoded this way, so the argument does not apply.
Exercise
A file loads without error using encoding="latin-1", but the city "Zürich" appears as "Zürich". What is the likely cause, and what should you try?
Show answer
The file is probably UTF-8, and latin-1 decoded each byte of the two-byte character ü as a separate character. Read it with encoding="utf-8" (or utf-8-sig if it has a byte order mark) and check the value again.
Exercise
You load a file with on_bad_lines="skip" and get 980 rows, but the file has 1,000 data lines. How do you find out which lines were dropped?
Show answer
Reload with on_bad_lines="warn". Each skipped line is reported with its line number, so you can inspect those lines in the source file.