DEV Community

Xiaoxue Tools
Xiaoxue Tools

Posted on

Cleaning a messy CSV without silently changing the numbers

Every "clean this export" task looks the same at the start: a file someone exported from a CRM, a marketplace back office, or a 12-year-old Access database. It opens fine, and the moment you start fixing it, you quietly lose money.

Here are the six things that actually break, and how to fix each one without destroying data.

1. Excel has already eaten your IDs

Open a CSV of order IDs in Excel and 0001234 becomes 1234. Anything 16 digits or longer becomes 1.23457E+15. Save, and the damage is now in the file.

Fix: never let Excel touch the raw file. Read as text first.

import pandas as pd

df = pd.read_csv("orders.csv", dtype=str, keep_default_na=False)
Enter fullscreen mode Exit fullscreen mode

dtype=str keeps every column as text. keep_default_na=False stops pandas from turning the literal string "NA" — a real country code — into a null.

2. Two date formats in the same column

13/05/2024 and 05/13/2024 can live in one column if two systems exported into it. Any parser that guesses will silently swap day and month for a third of your rows, and no error will be raised.

Fix: decide the format per row by inspection, not by trusting the parser.

def parse_date(s):
    s = s.strip()
    for fmt in ("%d/%m/%Y", "%d/%m/%y"):    # day-first, only if day > 12 is impossible to confuse
        try:
            d = pd.to_datetime(s, format=fmt, errors="raise")
            if d.day > 12:                    # unambiguous: must be day-first
                return d
        except ValueError:
            pass
    return pd.to_datetime(s, errors="coerce")
Enter fullscreen mode Exit fullscreen mode

The honest rule: only convert what you can prove. Leave ambiguous rows as text and flag them — a column that says "unclear" is worth more than a column that is confidently wrong.

3. Currency strings

$1,200.00 is a string. 1200 is a number. 1.200,00 (European) is a string that will parse as 1.200 if you get it wrong — a 1000x error.

def money(s):
    s = s.strip().replace("\u00a0", "")
    s = s.replace("$", "").replace("€", "").replace("£", "")
    if s.count(",") == 1 and s.count(".") == 1:
        s = s.replace(",", "") if s.rindex(",") < s.rindex(".") else s.replace(".", "").replace(",", ".")
    else:
        s = s.replace(",", "")
    return pd.to_numeric(s, errors="coerce")
Enter fullscreen mode Exit fullscreen mode

Then reconcile: the sum before and the sum after must match. If they don't, you didn't clean it, you changed it.

4. Duplicates that aren't duplicates

After trimming, " Ana" and "Ana " are the same person. Before trimming, they were two customers and a row that looks duplicated is actually a second order.

Fix: dedupe after normalization, on a key you chose deliberately, and keep the row with the most complete data rather than the first one.

df["name"] = df["name"].str.strip().str.replace(r"\s+", " ", regex=True)
df["join_date"] = df["join_date"].map(parse_date)
df = df.sort_values("amount_filled", ascending=False).drop_duplicates(subset=["id"], keep="first")
Enter fullscreen mode Exit fullscreen mode

5. Encoding

Windows exports are often cp1252 or latin-1, and a UTF-8 BOM shows up as \ufeff in front of your first header — which is why df["id"] sometimes raises KeyError on a column you can see.

df = pd.read_csv(path, dtype=str, encoding="utf-8-sig")   # handles the BOM
# fallback for old Windows exports:
df = pd.read_csv(path, dtype=str, encoding="cp1252")
Enter fullscreen mode Exit fullscreen mode

6. The trailing ghost rows

Exports from reporting tools append thousands of ,,,,, rows and sometimes a "Total" row that is a number in a column of text. They will wreck every aggregate you compute later.

df = df.dropna(how="all").loc[lambda d: d["id"].str.strip().ne("")]
Enter fullscreen mode Exit fullscreen mode

The habit that matters more than any of these

Print a before/after fingerprint for every column you touched: row count, null count, min, max, and the sum for numeric columns.

def fingerprint(df):
    return {c: (len(df), df[c].isna().sum(), df[c].nunique()) for c in df.columns}
Enter fullscreen mode Exit fullscreen mode

If a cleaning script can't explain what changed, it isn't cleaning, it's guessing. Delivering the cleaned file plus a short list of what changed and what was flagged is the difference between a task and a repair.


If you'd rather not write the script for one file: I built a browser-based cleaner that runs entirely locally, no upload, no signup — CSV cleaner. Drop the file, get the cleaned CSV plus a change report.

And if the file is genuinely ugly (multiple sheets, merged headers, mixed formats), that's what I do as a paid job — one file, 24-hour turnaround, cleaned file and change log.

Top comments (0)