← Guides

How to Clean a Messy CSV File with Python Pandas (Step by Step)

Encoding errors, mixed date formats, duplicated rows and numbers stored as text: a reproducible Pandas cleaning script you can adapt to any export.

Python · 10 min read

By the FormulAI editorial team · Reviewed November 19, 2026

Sample data used in this guide

Raw content of export.csv (; separator, Windows encoding). It contains stray spaces, amounts as text, a duplicate, an empty ";;;" row and two date formats.
Invoice NumberDateClient Amount
F-00103/01/2025Acme 1 250,00
F-00215/01/2025Borealis980,5
F-00215/01/2025Borealis980,5
F-0032025-02-01Cobaltn/a
F-00428/02/2025Delta3 400

Load the file without losing data

Exports from accounting or CRM tools are often encoded in Windows-1252 and use semicolons. Reading them with defaults produces garbled accents or a single column. Specify the separator and encoding explicitly, and read everything as text first so nothing is converted too early.

import pandas as pd

df = pd.read_csv("export.csv", sep=";", encoding="cp1252", dtype=str)
print(df.shape)
print(df.head())
Output of print(df.shape): 6 rows and 4 columns (the ";;;" row is kept as a row of missing values).
Output
(6, 4)

Normalize column names

Column names with spaces, capitals and accents make code fragile. Convert them to snake_case once, at the start of the script.

df.columns = (
    df.columns.str.strip()
    .str.lower()
    .str.normalize("NFKD").str.encode("ascii", "ignore").str.decode("ascii")
    .str.replace(r"[^a-z0-9]+", "_", regex=True)
)
Column names after normalization:
BeforeAfter
Invoice Numberinvoice_number
Datedate
Client client
Amountamount

Fix numbers stored as text

European exports write 1 234,56. Remove thousand separators, replace the decimal comma, then convert with errors="coerce" so invalid values become NaN instead of crashing. Always count the NaN produced: a sudden spike tells you the format assumption was wrong.

df["amount"] = pd.to_numeric(
    df["amount"].str.replace("\u00a0", "").str.replace(" ", "").str.replace(",", "."),
    errors="coerce",
)
print(df["amount"].isna().sum(), "invalid amounts")
amount column after conversion. The console prints "2 invalid amounts" (n/a and the empty row).
Original textFloat value
1 250,001250.0
980,5980.5
n/aNaN
3 4003400.0

Parse dates consistently

Mixed formats (12/03/2026 vs 2026-03-12) are the most dangerous issue because a wrong parse looks valid. Use dayfirst=True for European data and inspect the min and max dates to detect inversions.

df["date"] = pd.to_datetime(df["date"], dayfirst=True, errors="coerce")
print(df["date"].min(), df["date"].max())
With pandas 2 the format is inferred from the first row (dd/mm/yyyy), so F-003's ISO date becomes NaT. Add format="mixed" to recover it.
invoice_numberdate without formatdate with format="mixed"
F-0012025-01-032025-01-03
F-0022025-01-152025-01-15
F-003NaT2025-02-01
F-0042025-02-282025-02-28

Remove duplicates and blank rows

Decide which columns define a unique record (for example invoice number) before dropping duplicates; dropping on all columns misses rows that differ only by whitespace. Strip text columns first.

text_cols = df.select_dtypes("object").columns
df[text_cols] = df[text_cols].apply(lambda s: s.str.strip())
df = df.dropna(how="all").drop_duplicates(subset=["invoice_number"])
Final DataFrame: 4 unique invoices, no empty row, no stray spaces.
invoice_numberdateclientamount
F-0012025-01-03Acme1250.0
F-0022025-01-15Borealis980.5
F-0032025-02-01CobaltNaN
F-0042025-02-28Delta3400.0

Export and document

Write the cleaned file as UTF-8 so Excel and Google Sheets open it correctly, and log the number of rows removed at each step. Keeping these counts makes the cleaning auditable when a colleague asks why totals changed. You can paste a description of your own file into FormulAI to get a script tailored to your columns.

df.to_csv("export_clean.csv", index=False, encoding="utf-8-sig")

Common errors and how to fix them

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 12

Cause: The file comes from Excel on Windows and is cp1252-encoded: byte 0xe9 is an "é".

Fix: Pass encoding="cp1252" (or "latin-1") to read_csv.

ParserError: Error tokenizing data. C error: Expected 1 fields in line 3, saw 2

Cause: The file uses ; as separator while pandas expects a comma, so decimal commas create extra columns.

Fix: Set sep=";" explicitly.

KeyError: 'amount'

Cause: The column is still called "Amount" or "Amount " with spaces: normalization has not run yet.

Fix: Print list(df.columns) and run the normalization step before anything else.

AttributeError: Can only use .str accessor with string values!

Cause: The column was read as numbers (or already holds floats): .str only works on text.

Fix: Read the file with dtype=str, or convert first with df["amount"].astype(str).

FAQ

Why read the whole file as text (dtype=str)?

So pandas does not strip leading zeros (postcodes, references) or guess a type wrongly. You then convert each column deliberately.

Why utf-8-sig on export?

The BOM prefix lets Excel open the file with correct accents on a double-click, without the import wizard.

How do I keep track of rejected rows?

Before dropping them, save them: df[df["amount"].isna()].to_csv("rejected.csv"). You can then fix them at the source.

Go further

How this guide was made

Every formula, query and script in this guide was run on a real sample file (Excel 365, Google Sheets, PostgreSQL, MySQL or Python 3) before publication. We document the edge cases we hit during testing, such as text-formatted numbers, empty months or NULL values. AI helps us draft and translate; a human checks each example and updates the guide when software versions change. Spotted an error? Write to contact@formulai-app.com.