⚡0 XP🔥0

Cleaning Data with pandas

Lesson 4 of 7 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Clean the messy Vindhya Mart export step by step - duplicates, whitespace and case, spelling fixes, converting text to numbers, parsing mixed date formats safely, filling missing values by mapping, and validating the result.

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.

Practice file

sales_raw.csv (already loaded in every editor on this page)

▶ Try it Yourselfsales_raw.csvPython
Ctrl + Enter to run

Notice: sales is text (object/str), quantity is float (because of blanks), and order_date is text in several formats.

Step 1 - Duplicates#

▶ Try it Yourselfsales_raw.csvPython
Ctrl + Enter to run

drop_duplicates(subset=["order_id"], keep="first") would deduplicate on chosen columns only.

Step 2 - Text: spaces, case and spellings#

▶ Try it Yourselfsales_raw.csvPython
Ctrl + Enter to run
Tip

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#

▶ Try it Yourselfsales_raw.csvPython
Ctrl + Enter to run

errors="coerce" turns anything unconvertible into NaN - then you inspect those rows instead of crashing.

Step 4 - Mixed date formats (carefully!)#

▶ Try it Yourselfsales_raw.csvPython
Ctrl + Enter to run
हिंदी में समझें

तारीख़ों का जाल: 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#

▶ Try it Yourselfsales_raw.csv, sales.csvPython
Ctrl + Enter to run

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#

▶ Try it Yourselfsales_raw.csv, sales.csvPython
Ctrl + Enter to run

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.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Clean the city column

Load sales_raw.csv into raw. Create clean = raw without duplicate rows, with city trimmed, in Title Case, and Bangalore replaced by Bengaluru. Print the number of unique cities.

Dataset: sales_raw.csv (already loaded - just use the file name)
2

Fix the sales column

In sales_raw.csv, some sales values look like Rs. 2,099.30. Create a DataFrame df (duplicates removed) where sales is a numeric column, and total = the sum of sales rounded to 2 decimals.

Dataset: sales_raw.csv (already loaded - just use the file name)
3

Parse mixed dates safely

Convert order_date in sales_raw.csv (duplicates removed) into real dates in a DataFrame df. Dates come as 2024-04-25, 27/02/2024, 24-01-2024 and 17 Jun 2024 (day first). Parse ISO dates with format="%Y-%m-%d" first, then the rest with format="mixed", dayfirst=True, and combine with fillna. Create first_date and last_date (min and max).

Dataset: sales_raw.csv, sales.csv (already loaded - just use the file name)

Quick Quiz

Q1.

Which removes exact duplicate rows?

Q2.

Which converts ' indore ' to 'Indore'?

Q3.

What does pd.to_numeric(s, errors="coerce") do with a value it can't convert?

Q4.

Why can dayfirst=True be dangerous on a column that also contains ISO dates (2024-03-12)?

Q5.

Which fills a missing region using each row's city?