The messy file#
sales_raw.csv is a typical export: 312 rows with duplicates, inconsistent text, amounts stored as text, mixed date formats and blanks. You cleaned it in Excel; now let's write a repeatable cleaning script - run it again next month in one second.
sales_raw.csv (already loaded in every editor on this page)
Notice: sales is text (object/str), quantity is float (because of blanks), and order_date is text in several formats.
Step 1 - Duplicates#
drop_duplicates(subset=["order_id"], keep="first") would deduplicate on chosen columns only.
Step 2 - Text: spaces, case and spellings#
For many spelling variants, keep a mapping dictionary in one place: CITY_FIX = {"Bangalore": "Bengaluru", "Bombay": "Mumbai", "Gurgaon": "Gurugram"} and apply it with .replace(CITY_FIX).
Step 3 - Text to numbers#
errors="coerce" turns anything unconvertible into NaN - then you inspect those rows instead of crashing.
Step 4 - Mixed date formats (carefully!)#
तारीख़ों का जाल: India में हम दिन पहले लिखते हैं (27/02/2024), इसलिए dayfirst=True देना ज़रूरी है। लेकिन इसी column में अगर 2024-03-12 (ISO format - साल-महीना-दिन) भी है, तो dayfirst=True उसे भी उल्टा पढ़कर 3 दिसंबर बना देता है - और कोई error नहीं आता!
सुरक्षित तरीका: पहले ISO वाली तारीख़ें साफ़ format (%Y-%m-%d) से पढ़ें, बाकी बची हुई dayfirst=True से, और दोनों को fillna से जोड़ दें। हमेशा कुछ तारीख़ें हाथ से जाँचें।
Step 5 - Missing values#
Options for missing values:
| Method | Use when |
|---|---|
df.dropna(subset=["col"]) |
the row is useless without that value |
df["col"].fillna(0) |
missing truly means zero (e.g. no returns) |
df["col"].fillna(df["col"].median()) |
a typical value is acceptable (be careful - document it) |
fillna(df["key"].map(lookup)) |
it can be derived from another column |
df["col"].ffill() |
time series / sheets where blanks mean "same as above" |
| flag and keep | you need to ask the data owner |
Step 6 - Validate#
Never trust a cleaning script without checks:
assert df["order_id"].is_unique
assert df["sales"].ge(0).all()
assert df["order_date"].between("2024-01-01", "2025-12-31").all()
assert df["region"].isin(["North", "South", "East", "West", "Central"]).all()
print("All checks passed")
The complete reusable script#
Summary#
- Work on a copy; deduplicate with
drop_duplicates. - Clean text with
.str.strip(),.str.title(),.replace(mapping). - Convert numbers with string replacements +
pd.to_numeric(errors="coerce"). - Parse mixed dates carefully: explicit ISO format first, then
dayfirst=True; spot-check results. - Handle missing values deliberately (drop, fill, derive with
map, or flag). - Validate with
asserts and wrap the steps in a reusable function.