Cleaning missing and duplicate data
Python · 15 questions
Short notes
Key idea
Before analysis, find and fix missing values and duplicates. Decide per column: drop, fill, or keep and flag.
Syntax
df.isna().sum() # missing per column
df.dropna(subset=["amount"])
df["city"] = df["city"].fillna("Unknown")
df["amount"] = df["amount"].fillna(df["amount"].median())
df.duplicated().sum()
df.drop_duplicates()
df.drop_duplicates(subset=["order_id"], keep="last")
df["amount"] = pd.to_numeric(df["amount"], errors="coerce")
Example
print(len(df))
df = df.drop_duplicates(subset=["order_id"])
df = df.dropna(subset=["customer_id"])
print(len(df)) # always report how many rows you removed
Traps
- Filling with 0 changes averages. Use the median, or leave NaN, when 0 isn't a real value.
dropna()with nosubsetdrops a row if any column is empty, often far too many.- Duplicates depend on the key: whole-row duplicates and repeated
order_ids are different checks. - Text like "NA", "-" or "" isn't NaN until you convert it (
na_values=inread_csv).
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
You want to drop rows only where
emailis missing. Which line does that? - Question 2medium
Two customers have the same first and last name but different emails. What should you do?
- Question 3medium
Two pairs of customers share a name: two Priya Sharmas and two Arun Kumars. What does this print?
print(customers.duplicated(subset=["first_name", "last_name"]).sum())
- Question 4medium
20 of the 80 orders are pending or cancelled, so they have no
shipped_date. 2 other orders have nopayment_method. What does this print?print(len(orders.dropna()))
- Question 5hard
Store in
resultone row per customer fromorders: their latest order byorder_date(break ties by the higherorder_id).The tables are ready as DataFrames with the same names. Store your answer in
result.Tables
Cleaning missing and duplicate data
Cleaning missing and duplicate data
Cleaning missing and duplicate data
Cleaning missing and duplicate data
Cleaning missing and duplicate data
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.