Pandas read_csv for Messy CSV Files (Step by Step)

The pandas read_csv function loads a CSV file into a DataFrame, which is pandas’ table of rows and columns. On a clean file, pd.read_csv("file.csv") is the whole job. Real exports are rarely clean, and a handful of parameters fix almost everything they throw at you. Those are encoding, skiprows, on_bad_lines, dtype, na_values, thousands and date_format.

In this post I load one messy export with pandas read_csv and fix it one error at a time. Three of its problems crash right away. Three are worse, because pandas loads the file without a word and hands you wrong data.

I use read_csv at work as a data and backend developer, and to build the examples for posts here. The encoding error and the swapped day and month have both bitten me, so they get the most space here.

Every code block below ran on Python 3.14.7, pandas 3.1.0 and pyarrow 26.0.0 on a Mac, and the output shown is what it printed. pandas 3.1.0 came out on October 22, 2026. It changed the order of the first errors and the speed of big reads, and I point out both where they come up. The order data is made up for this post.

Which read_csv parameter fixes which problem?

Here’s the short answer. Each row is a symptom, the parameter that fixes it, and the step that shows it on a real file.

What you see What fixes it Step
ParserError saying Expected 1 fields near the top skiprows=2 or comment="#" 3
ParserError saying Expected 7 fields ... saw 8 on_bad_lines="warn" 4
UnicodeDecodeError: 'utf-8' codec can't decode byte encoding="cp1252" 5
00127 loads as 127 dtype={"order_id": "str"} 7
A money column loads as text thousands="," and na_values=["-"] 8
Everything lands in one or two columns sep=";", decimal="," and header=None 8
Dates stay text or land in the wrong month date_format="%d/%m/%Y" 9
A big file is slow or won’t fit in memory pandas 3.1, usecols, chunksize 10
An Unnamed: 0 column after saving to_csv(..., index=False) 11

What do you need before you start?

You need three things.

The 11 steps at a glance

Steps 1 to 5 get the file to load at all. Steps 6 to 9 fix what loaded wrong without telling you. Steps 10 and 11 are for big files and saving.

  1. Install pandas 3 and pyarrow.
  2. Look at the messy file first.
  3. Skip the junk lines at the top.
  4. Handle rows with too many fields.
  5. Fix the UnicodeDecodeError with encoding.
  6. Check what pandas guessed with info().
  7. Keep leading zeros with dtype.
  8. Turn placeholders and commas into numbers.
  9. Parse day-first dates without silent mistakes.
  10. Load big files faster.
  11. Write the CSV back without Unnamed 0.

Step 1. Install pandas 3 and pyarrow

Make a virtual environment first. That’s a private folder of packages for one project, so nothing here clashes with the rest of your Python setup.

python3 -m venv .venv
source .venv/bin/activate
pip install "pandas>=3" pyarrow

pyarrow is optional, but install it. pandas 3 stores text columns with it when it’s there, which cuts memory a lot (Step 10 has the numbers). It also adds a second CSV reader, engine="pyarrow".

Check the version.

import pandas as pd

print(pd.__version__)
3.1.0

Step 2. Look at the messy file first

Here’s orders.csv, an order export from a made-up shop admin. Open any CSV in a plain text editor before you load it. It takes ten seconds and saves the next twenty minutes.

# Exported from the shop admin on 2026-10-14
# Do not edit by hand
order_id,customer,zip,city,order_date,amount,status
00127,Ana Lima,02134,Boston,03/10/2026,"1,250.00",shipped
00128,Ben Okafor,10001,New York,04/10/2026,89.99,shipped
00129,Chloé Martin,94103,San Francisco,05/10/2026,N/A,pending
00130,Dev Patel,60601,Chicago,13/10/2026,430.50,shipped,GIFT
00131,Eve Chen,98101,Seattle,14/10/2026,-,cancelled
00132,Farah Khan,30301,Atlanta,15/10/2026,"2,100.00",shipped

Count the problems.

  • Two comment lines sit above the header.
  • The file is saved in cp1252, the encoding Excel on Windows often uses, not UTF-8. You can’t see that in an editor, but the é in Chloé is stored differently.
  • Order IDs and ZIP codes start with zeros.
  • The amount column has quotes, commas, “N/A” and a lone “-”.
  • Dates are day first. 03/10/2026 means 3 October.
  • Dev Patel’s row has an eighth field, GIFT, with no column for it.

Real exports look like this all the time. Nobody tells the person who built the export.

Step 3. Skip the junk lines at the top

The first try is the obvious call.

df = pd.read_csv("orders.csv")
ParserError: Error tokenizing data. C error: Expected 1 fields in line 3, saw 7

pandas took the first line, # Exported from the shop admin..., as the header. That’s one field. Line 3 is the real header with seven, so the parser gives up.

skiprows=2 drops the first two lines of the file before reading the header.

df = pd.read_csv("orders.csv", skiprows=2)
ParserError: Error tokenizing data. C error: Expected 7 fields in line 7, saw 8

New error, which is progress.

comment="#" works too. It ignores everything after a # on any line, which also catches comment lines further down. It also cuts any value that contains a #, like an address with “Apt #4”, so skiprows is the safer pick when you know the exact count.

Step 4. Handle rows with too many fields

Line 7 is Dev Patel’s row with the extra GIFT field. By default read_csv raises an error on a bad line, so one broken row stops the whole file. The on_bad_lines parameter decides what happens instead.

  • "error" is the default. It stops, as above.
  • "warn" skips the row and tells you.
  • "skip" skips it silently, which is how a finance report ends up one order short and nobody knows why.
df = pd.read_csv("orders.csv", skiprows=2, on_bad_lines="warn")
ParserWarning: Skipping line 7: expected 7 fields, saw 8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 4: invalid continuation byte

The bad row is skipped with a warning, and the next problem shows up right behind it.

Step 5. Fix the UnicodeDecodeError with encoding

An encoding is the rule that turns bytes into letters. read_csv assumes UTF-8. Byte 0xe9 is é in cp1252, but in UTF-8 that byte can’t sit where it does, so decoding stops. Position 4 is the fifth byte of “Chloé Martin”, right after “Chlo”.

On pandas 3.0 and older, this is the very first error you get, before the two in Steps 3 and 4. I ran the first try on pandas 2.3.3, 3.0.6 and 3.1.0, and only 3.1.0 reported the junk lines and the extra field first. So if your error order doesn’t match this post, check pd.__version__.

Tell pandas the real encoding. It’s the same encoding idea as Python’s own open(), which my post on reading and writing files in Python covers.

df = pd.read_csv("orders.csv", encoding="cp1252", skiprows=2, on_bad_lines="warn")
print(len(df))
ParserWarning: Skipping line 7: expected 7 fields, saw 8
5

It loads now, with 5 rows instead of 6. If you don’t know a file’s encoding, "cp1252" is the usual suspect for files from Excel on Windows. Don’t use encoding_errors="ignore" to make the error go away. It does, by deleting the é. Chloé Martin comes out as “Chlo Martin”.

In a script that loads a new file every day, catch UnicodeDecodeError and pd.errors.ParserError with try and except, so one bad file gets logged instead of stopping the whole run. My post on exception handling in Python shows how.

How do you keep the bad rows instead of dropping them?

With engine="python", on_bad_lines also takes a function. pandas calls it with the bad row’s fields, and returning None drops the row, as the read_csv docs describe.

bad_rows = []


def keep_bad_row(fields):
    bad_rows.append(fields)
    return None  # None drops the row from the DataFrame


df = pd.read_csv(
    "orders.csv",
    encoding="cp1252",
    skiprows=2,
    on_bad_lines=keep_bad_row,
    engine="python",
)
print(len(df))
print(bad_rows)
5
[['00130', 'Dev Patel', '60601', 'Chicago', '13/10/2026', '430.50', 'shipped', 'GIFT']]

Now the row is out of the table but not lost. You can log it, fix it, or send it back to whoever made the export.

Step 6. Check what pandas guessed with info()

The file loads. That’s when people stop checking, and it’s exactly when the quiet problems start. info() shows each column’s dtype, which is the data type pandas picked for it, and how many values aren’t missing.

df.info()
print(df[["order_id", "zip", "amount"]])
<class 'pandas.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 7 columns):
 #   Column      Non-Null Count  Dtype
---  ------      --------------  -----
 0   order_id    5 non-null      int64
 1   customer    5 non-null      str  
 2   zip         5 non-null      int64
 3   city        5 non-null      str  
 4   order_date  5 non-null      str  
 5   amount      4 non-null      str  
 6   status      5 non-null      str  
dtypes: int64(2), str(5)
memory usage: 612.0 bytes
   order_id    zip    amount
0       127   2134  1,250.00
1       128  10001     89.99
2       129  94103       NaN
3       131  98101         -
4       132  30301  2,100.00

Three columns are wrong, and nothing warned about any of them.

  • order_id and zip became integers, so 00127 is now 127 and Boston’s 02134 is 2134.
  • amount is text, because “1,250.00” and “-” aren’t numbers to pandas.
  • order_date is text too. Step 9 covers it.

The str dtype is new in pandas 3. Older versions said object here. More on that in the last section.

Step 7. Keep leading zeros with dtype

ZIP codes, order IDs and phone numbers look like numbers but aren’t. You never add two ZIP codes together. Pass dtype and pandas stops guessing for those columns.

df = pd.read_csv(
    "orders.csv",
    encoding="cp1252",
    skiprows=2,
    on_bad_lines="skip",
    dtype={"order_id": "str", "zip": "str"},
)
print(df[["order_id", "zip"]])
  order_id    zip
0    00127  02134
1    00128  10001
2    00129  94103
3    00131  98101
4    00132  30301

The zeros are back. A simple rule covers it. If a column is an ID or a code, read it as text.

Step 8. Turn placeholders and commas into numbers

The amount column has two problems. “1,250.00” uses a comma as a thousands separator, and “-” means “no amount”. pandas already treats “N/A” as missing, since it’s on its default list along with “NULL”, “NaN” and empty cells. “-” isn’t on that list, so add it with na_values.

df = pd.read_csv(
    "orders.csv",
    encoding="cp1252",
    skiprows=2,
    on_bad_lines="skip",
    dtype={"order_id": "str", "zip": "str"},
    na_values=["-"],
    thousands=",",
)
print(df[["order_id", "amount"]])
print(df["amount"].dtype, df["amount"].sum())
  order_id   amount
0    00127  1250.00
1    00128    89.99
2    00129      NaN
3    00131      NaN
4    00132  2100.00
float64 3439.99

amount is a real number column now, and the sum works. NaN is pandas’ marker for a missing value, and sum() skips it.

What if the file uses semicolons and decimal commas?

Many European exports put a semicolon between fields and use a comma as the decimal point, with a dot for thousands. Here’s orders_eu.csv, three more made-up orders with no header row.

00133;Greta Weber;10115;Berlin;16/10/2026;1.250,00;shipped
00134;Hugo Laurent;75001;Paris;17/10/2026;89,99;pending
00135;Ines Costa;01000;Lisbon;18/10/2026;2.100,50;shipped

The default read doesn’t fail.

eu = pd.read_csv("orders_eu.csv")
print(eu.shape)
print(eu.columns.tolist())
(2, 2)
['00133;Greta Weber;10115;Berlin;16/10/2026;1.250', '00;shipped']

pandas split each line at the only comma it found, the decimal comma, and used the first order as the header. Two rows, two columns, zero errors.

Four settings fix it. sep sets the separator. decimal and thousands set the number format. header=None says there’s no header row, and names gives the columns their names.

eu = pd.read_csv(
    "orders_eu.csv",
    sep=";",
    decimal=",",
    thousands=".",
    header=None,
    names=["order_id", "customer", "zip", "city", "order_date", "amount", "status"],
    dtype={"order_id": "str", "zip": "str"},
)
print(eu[["order_id", "zip", "city", "amount"]])
print(eu["amount"].dtype)
  order_id    zip    city   amount
0    00133  10115  Berlin  1250.00
1    00134  75001   Paris    89.99
2    00135  01000  Lisbon  2100.50
float64

If you don’t know the separator, sep=None makes pandas guess it with Python’s csv.Sniffer. The docs note that this only works with the slower Python engine, which pandas then switches to on its own.

Step 9. Parse day-first dates without silent mistakes

This is the step that bit me, and it’s the one most tutorials skip. parse_dates asks pandas to turn a column into real dates. Here’s what it does with day-first dates.

df = pd.read_csv(
    "orders.csv",
    encoding="cp1252",
    skiprows=2,
    on_bad_lines="skip",
    parse_dates=["order_date"],
)
print(df["order_date"].dtype)
str

You asked for dates and got text, with no error and no warning. pandas guesses the format from the first value, 03/10/2026, and guesses month first. Then 14/10/2026 doesn’t fit, so it gives up and leaves the whole column as text.

That’s the good outcome. Here’s the same file read with only the first three rows, where every day is 12 or lower.

df = pd.read_csv(
    "orders.csv",
    encoding="cp1252",
    skiprows=2,
    on_bad_lines="skip",
    parse_dates=["order_date"],
    nrows=3,
)
print(df[["order_id", "order_date"]])
   order_id order_date
0       127 2026-03-10
1       128 2026-04-10
2       129 2026-05-10

Those orders were placed on 3, 4 and 5 October. pandas filed them under March, April and May, again with no warning. With a file of only early-month dates, you’d never know. pandas 2.3.3 gave the same three wrong months, so this isn’t new in pandas 3.

There are two fixes. dayfirst=True tells the guesser to put the day first.

df = pd.read_csv(
    "orders.csv",
    encoding="cp1252",
    skiprows=2,
    on_bad_lines="skip",
    parse_dates=["order_date"],
    dayfirst=True,
)
print(df["order_date"].dt.strftime("%d %b %Y").tolist())
['03 Oct 2026', '04 Oct 2026', '05 Oct 2026', '14 Oct 2026', '15 Oct 2026']

The better fix is date_format, which removes the guessing completely. If a date doesn’t match the format, pandas tells you instead of inventing one. Here’s the full read with every fix so far.

df = pd.read_csv(
    "orders.csv",
    encoding="cp1252",
    skiprows=2,
    on_bad_lines="skip",
    dtype={"order_id": "str", "zip": "str"},
    na_values=["-"],
    thousands=",",
    parse_dates=["order_date"],
    date_format="%d/%m/%Y",
)
print(df[["order_id", "order_date"]])
df.info()
  order_id order_date
0    00127 2026-10-03
1    00128 2026-10-04
2    00129 2026-10-05
3    00131 2026-10-14
4    00132 2026-10-15
<class 'pandas.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 7 columns):
 #   Column      Non-Null Count  Dtype         
---  ------      --------------  -----         
 0   order_id    5 non-null      str           
 1   customer    5 non-null      str           
 2   zip         5 non-null      str           
 3   city        5 non-null      str           
 4   order_date  5 non-null      datetime64[us]
 5   amount      3 non-null      float64       
 6   status      5 non-null      str           
dtypes: datetime64[us](1), float64(1), str(5)
memory usage: 589.0 bytes

Every column now has the right type. %d/%m/%Y means day, month, then four-digit year. The codes are listed in Python’s strftime reference.

Step 10. Load big files faster

For speed I made a clean, made-up file of 1,000,000 orders, about 51 MB, and timed five ways to read it on an M2 Max Mac. I ran each one on pandas 2.3.3, 3.0.6 and 3.1.0. Each time is the best of three runs. Memory is what the DataFrame takes up, from memory_usage(deep=True).

How I read the 1,000,000-row file pandas 2.3.3 pandas 3.0.6 pandas 3.1.0
pd.read_csv(path) 0.329 s, 243 MB 0.429 s, 79 MB 0.015 s, 79 MB
engine="pyarrow" 0.069 s, 224 MB 0.029 s, 101 MB 0.026 s, 101 MB
usecols with 3 of 6 columns 0.199 s, 121 MB 0.242 s, 39 MB 0.055 s, 39 MB
dtype="category" for city and status 0.318 s, 132 MB 0.372 s, 50 MB 0.030 s, 50 MB
parse_dates=["order_date"] 0.390 s, 192 MB 0.528 s, 69 MB 0.089 s, 69 MB
Default read_csv time and memory on pandas 2.3.3, 3.0.6 and 3.1.0 Two bar charts for the default read of a 1,000,000-row CSV file. Seconds to read, pandas 2.3.3 0.329, 3.0.6 0.429, 3.1.0 0.015. Memory, pandas 2.3.3 243 MB, 3.0.6 79 MB, 3.1.0 79 MB. Seconds to read the file pandas 2.3.3 0.329 s pandas 3.0.6 0.429 s pandas 3.1.0 0.015 s Memory after reading pandas 2.3.3 243 MB pandas 3.0.6 79 MB pandas 3.1.0 79 MB
The default read of the same 1,000,000-row file on three pandas versions, best of three runs on an M2 Max Mac. pandas 3.0 cut the memory and pandas 3.1 cut the time. Bars are drawn from the first row of the table above.
Drawn with Python from bench.py's output.

Here’s what the numbers show.

  • pandas 3.0 cut memory by about two thirds, from 243 MB to 79 MB, with no code change. That’s the new pyarrow-backed str type. Its default reader was a little slower than 2.3.3’s in my runs, 0.429 s against 0.329 s.
  • pandas 3.1 made the default reader about 29 times faster than 3.0.6 on this file, 0.015 s against 0.429 s. It now reads big files on several CPU threads, up to 6 by default. On one thread it took 0.070 s, so each thread got faster too.
  • On pandas 3.1 the default reader beat engine="pyarrow", 0.015 s against 0.026 s. On pandas 3.0 and older, pyarrow was the fast option by a wide margin.
  • usecols still halves memory, but on 3.1 it turns off the parallel read, so it was slower than loading every column. The docs list the options that do this, including usecols, parse_dates, nrows, chunksize and any encoding other than UTF-8.
  • category stores each repeated value once, which helps columns with a few values repeated many times, like city or status. Don’t use it for codes. On pandas 3.1, a ZIP code column read as category came back with 2134 instead of 02134, because 3.1 now turns number-like categories into numbers.

Your times will differ. The gaps between rows are the part that carries over.

The pyarrow engine also supports fewer options. On the messy file from Step 2 it refused outright.

pd.read_csv("orders.csv", engine="pyarrow", encoding="cp1252", comment="#")
ValueError: The 'comment' option is not supported with the 'pyarrow' engine

So on pandas 3.1 the default engine is the one to use for messy files and big ones. On older versions, pyarrow is worth it for big, clean files.

What if the file doesn’t fit in memory?

Pass chunksize, and read_csv hands you the file in pieces instead of one DataFrame. This adds up the order amounts by status, 250,000 rows at a time.

totals = {}
for chunk in pd.read_csv("orders_big.csv", usecols=["status", "amount"], chunksize=250_000):
    for status, amount in chunk.groupby("status")["amount"].sum().items():
        totals[status] = totals.get(status, 0) + amount
print({k: round(v, 2) for k, v in sorted(totals.items())})
{'cancelled': 627304804.81, 'pending': 623894459.17, 'refunded': 623592386.27, 'shipped': 625921349.02}

Only one chunk is in memory at a time. It works for anything you can compute piece by piece, like sums, counts and filters.

Step 11. Write the CSV back without Unnamed 0

to_csv writes the DataFrame’s index, its row numbers, as an extra first column unless you tell it not to. Read that file back and you get a column called Unnamed: 0.

df.to_csv("orders_clean.csv")
print(pd.read_csv("orders_clean.csv").columns.tolist())

df.to_csv("orders_clean.csv", index=False)
print(pd.read_csv("orders_clean.csv").columns.tolist())
['Unnamed: 0', 'order_id', 'customer', 'zip', 'city', 'order_date', 'amount', 'status']
['order_id', 'customer', 'zip', 'city', 'order_date', 'amount', 'status']

Write with index=False, or read with index_col=0 if the index means something.

Watch out for one more thing. A CSV stores text, not types, so the fixes from Steps 7 to 9 don’t travel with the file.

back = pd.read_csv("orders_clean.csv")
print(back[["order_id", "zip"]].head(2))
   order_id    zip
0       127   2134
1       128  10001

The zeros are gone again. Pass the same dtype every time you read the file. If you need the types to survive a save, use a format that stores them, like Parquet with df.to_parquet(). JSON keeps numbers and true or false values but has no date type, which my post on JSON with Python runs into.

What changed in pandas 3 since my 2023 post?

I first wrote about pandas CSVs in March 2023 with the Google Play Store dataset from Kaggle, 10,841 apps in 13 columns. Here’s part of what info() printed back then.

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10841 entries, 0 to 10840
Data columns (total 13 columns):
 #   Column          Non-Null Count  Dtype  
---  ------          --------------  -----  
 0   App             10841 non-null  object 
 1   Category        10841 non-null  object 
 2   Rating          9367 non-null   float64
 3   Reviews         10841 non-null  object 
...
dtypes: float64(1), object(12)
memory usage: 1.1+ MB

Twelve of thirteen columns were object, including Reviews, which should be a number. That file had a broken row too. Row 10472 had “1.9” as its category and 19.0 as its rating, on a 1 to 5 scale. Its values sit one column off, and the row went straight through read_csv without a peep. Same lesson as Step 6, three years earlier.

To see what changed, I ran the same full read from Step 9 on pandas 2.3.3, 3.0.6 and 3.1.0, all on Python 3.14.7.

pandas 2.3.3 pandas 3.0.6 pandas 3.1.0
Text columns object str str
Dates from parse_dates datetime64[ns] datetime64[us] datetime64[us]
What type(df) prints pandas.core.frame.DataFrame pandas.DataFrame pandas.DataFrame
Memory, 1,000,000-row file 243 MB 79 MB 79 MB
Default read time, same file 0.329 s 0.429 s 0.015 s
First error on orders.csv UnicodeDecodeError UnicodeDecodeError ParserError
df["status"][0] = "refunded" Changes the value, with a warning Changes nothing, with a warning Changes nothing, with a warning

The pandas 3.0 release notes cover the type changes, and the 3.1 release notes cover the faster reader. pandas 3.0 came out on January 21, 2026, and 3.1 on October 22, 2026. The dates now default to microseconds instead of nanoseconds, and the 3.0 notes warn that converting those dates to integers gives numbers 1,000 times smaller.

The last row of the table can break old code without an error. pandas 3 always uses Copy-on-Write, which means any selection behaves like a copy. So the two-step df["status"][0] = ..., called chained assignment, writes into a copy and the original never changes.

df.loc[0, "status"] = "shipped"
df["status"][0] = "refunded"
print(df.loc[0, "status"])

df.loc[0, "status"] = "refunded"
print(df.loc[0, "status"])
ChainedAssignmentError: A value is being set on a copy of a DataFrame or Series through chained assignment.
shipped
refunded

The first line is a warning, not a crash, and the script keeps going with the old value. df.loc[row, column] = value in one step is the version that works on every pandas.

If your code checks dtype == object to find text columns, it stops matching on pandas 3. Use pd.api.types.is_string_dtype(df[col]) instead.

What should you remember about pandas read_csv?

  • Open the file in a text editor before you load it.
  • A UnicodeDecodeError means the wrong encoding. Try encoding="cp1252" for files from Excel on Windows.
  • Use skiprows for junk lines above the header.
  • Use on_bad_lines="warn", or a function with engine="python", so broken rows don’t vanish quietly.
  • Use sep, decimal and header=None with names for semicolon files without a header row.
  • Always run df.info() after loading.
  • Read IDs, ZIP codes and phone numbers with dtype="str".
  • Use na_values for your file’s own missing-value markers and thousands="," for formatted numbers.
  • Never trust parse_dates with day-first dates. Pass date_format.
  • For big files, upgrade to pandas 3.1 first. Then use usecols or category to save memory, and chunksize for files bigger than memory.
  • Write with index=False, and pass your dtype again on every read.

Once the data loads cleanly, my linear regression in Python tutorial picks it up from a DataFrame and fits a model to it. For a bigger real dataset, my sklearn linear regression tutorial reads the NFL Combine CSV straight from a URL.

What’s the worst thing a CSV file has done to you after it loaded without an error?