Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Data Analytics Course data cleaning intermediate pandas Phase 5 — Python for Analytics Python

Handling Missing Values and Duplicates in pandas

Reviewed & accurate
AI Summary

What You Will Learn

  • How to find missing values in a DataFrame
  • Three strategies: drop, fill, or leave them alone
  • How to find and remove duplicates
  • Why "cleaning" is not optional — it changes your results

Why This Topic Matters

Real datasets are never clean. Customer support logs have empty fields. Survey responses skip questions. Two systems merge and create duplicate customer records. If you do not handle missing values and duplicates before analysis, your averages will be wrong, your counts will be inflated, and your joins will multiply rows. This lesson teaches the cleaning steps every dataset needs.

The Messy Dataset

import pandas as pd
import numpy as np

df = pd.DataFrame({
    "order_id": [1, 2, 3, 4, 5, 3],
    "customer": ["Anita", "Ravi", "Mira", "Sam", "Anita", "Mira"],
    "city":     ["Mumbai", np.nan, "Kolkata", "Mumbai", "Mumbai", "Kolkata"],
    "amount":   [500, 1200, np.nan, 900, 500, np.nan],
    "rating":   [5, 4, np.nan, 2, 5, np.nan]
})
print(df)
   order_id customer     city   amount  rating
0         1    Anita   Mumbai   500.0     5.0
1         2     Ravi      NaN  1200.0     4.0
2         3     Mira  Kolkata     NaN     NaN
3         4      Sam   Mumbai   900.0     2.0
4         5    Anita   Mumbai   500.0     5.0
5         3     Mira  Kolkata     NaN     NaN

This dataset has it all: a missing city, missing amounts, missing ratings, and a duplicate row (order_id 3 appears twice).

1. Finding Missing Values

df.isna()              # True/False for every cell
df.isna().sum()        # count of NaNs per column
# order_id    0
# customer    0
# city        1
# amount      2
# rating      2
# dtype: int64

df.isna().sum().sum()  # total NaNs in the DataFrame → 5

# Rows with any NaN
df[df.isna().any(axis=1)]

# Rows where ALL values are NaN
df[df.isna().all(axis=1)]

2. Three Strategies for Missing Values

Strategy A — Drop rows with NaN

df.dropna()                     # drop rows with ANY NaN
df.dropna(how="all")            # drop rows where ALL values are NaN
df.dropna(subset=["amount"])    # drop rows where amount is NaN
df.dropna(subset=["amount", "rating"])  # drop if either is NaN

Use when: the NaN rows are few, and dropping them does not bias your analysis.

Avoid when: dropping removes a meaningful chunk of data (say >5%) or systematically removes one type of row.

Strategy B — Fill missing values

df["amount"].fillna(0)                       # fill with 0
df["rating"].fillna(df["rating"].mean())     # fill with mean
df["rating"].fillna(df["rating"].median())   # fill with median
df["city"].fillna("Unknown")                 # fill text with a label
df["amount"].fillna(df["amount"].median(), inplace=True)  # in place

Use when: the column is important and dropping rows would lose too much data.

Warning: filling with mean or median can hide real patterns. If 30% of ratings are missing, filling them all with the mean makes your distribution look more "average" than it really is. Document your choice.

Strategy C — Leave them alone

Sometimes the right move is to do nothing. pandas aggregations (sum, mean, count) skip NaN by default, just like SQL. If you only need totals and averages, NaNs in non-key columns do not matter.

Use when: the NaN column is not central to your analysis and you are only computing aggregates that skip NaN.

Choosing the Right Strategy — A Decision Guide

SituationStrategy
Few rows with NaN (<5% of data)Drop them
Many rows with NaN, column is criticalFill with a sensible default (median, mode, or "Unknown")
Many rows with NaN, column is not usedLeave alone or drop the column
NaN itself is meaningful (e.g., "no complaint")Fill with a label that captures the meaning
Time-series data with gapsForward-fill (ffill) or interpolate

3. Handling Duplicates

df.duplicated()           # True for rows that are duplicates of earlier rows
df.duplicated().sum()     # count of duplicate rows → 1

df.drop_duplicates()                       # drop fully duplicated rows
df.drop_duplicates(subset=["order_id"])    # drop rows with duplicate order_id, keep first
df.drop_duplicates(subset=["order_id"], keep="last")  # keep last instead

Real-world duplicate causes

  • Same record synced twice. Two systems both write the same order. Drop by order_id.
  • Same customer under two IDs. Different customer_id but same email. Harder — needs fuzzy matching.
  • Multiple events on the same day. A customer placing two orders in one day is NOT a duplicate. Be careful with subset=["customer", "date"] — you may drop legitimate rows.
Always inspect duplicates before dropping. Run df[df.duplicated(subset=["order_id"], keep=False)] to see all duplicate rows together. Confirm they really are duplicates before deleting.

4. Type Conversion — The Hidden Cleaning Step

Numbers stored as text are a silent killer. Check types and convert:

df.dtypes
# order_id      int64
# customer     object
# city         object
# amount      float64   # became float because of NaN
# rating      float64

# Convert text-stored numbers
df["order_id"] = df["order_id"].astype(str)         # ID as text (correct)
df["amount"] = pd.to_numeric(df["amount"], errors="coerce")  # text → number, NaN if invalid

# Convert dates
df["ordered_at"] = pd.to_datetime(df["ordered_at"])

errors="coerce" turns invalid values (like "N/A") into NaN instead of crashing. Always use it when converting user-supplied text to numbers.

5. String Cleaning

Text columns often have leading/trailing spaces and inconsistent case:

df["customer"] = df["customer"].str.strip()        # remove whitespace
df["customer"] = df["customer"].str.title()        # "anita" → "Anita"
df["city"] = df["city"].str.upper()                # "mumbai" → "MUMBAI"

"Mumbai" and "Mumbai " are different strings — they will not match in a groupby. Always strip text columns before grouping or joining.

Putting It All Together — A Cleaning Pipeline

clean = (df
  .drop_duplicates(subset=["order_id"])                          # 1. Dedupe
  .assign(
      customer=lambda x: x["customer"].str.strip().str.title(),  # 2. Clean text
      city=lambda x: x["city"].fillna("Unknown"),                # 3. Fill city
      amount=lambda x: x["amount"].fillna(x["amount"].median())  # 4. Fill amount
  )
  .drop(columns=["rating"])                                      # 5. Drop unused
  .reset_index(drop=True)                                        # 6. Clean index
)
print(clean)

This single chain takes the messy DataFrame and produces a clean one. Each step is documented by the method name itself.

Common Mistakes

  1. Dropping NaN rows without checking the percentage. If 30% of rows have NaN in one column, dropping them loses 30% of your data — and probably a non-random 30%.
  2. Filling with mean when the data is skewed. Outliers pull the mean up; filling with median is usually safer.
  3. Forgetting that dropna and fillna return new DataFrames by default. Either assign the result or pass inplace=True.
  4. Dropping duplicates without inspecting them first. You might drop legitimate rows that just happen to share a key.
  5. Not cleaning text before joining. " Mumbai " and "Mumbai" are different strings — the join silently produces fewer matches than expected.

Practical Exercise (20 minutes)

  1. Create the messy DataFrame above.
  2. Count NaNs per column. Which column has the most?
  3. Drop fully duplicate rows.
  4. Fill missing city with "Unknown" and missing amount with the median.
  5. Drop the rating column entirely (assume it is not needed for this analysis).
  6. Strip whitespace from customer and title-case it.
  7. Confirm the final DataFrame has no NaN and no duplicates.

Mini Challenge

Find a real CSV with at least some missing values (most public datasets have them — try Kaggle's "Titanic" dataset). Load it into pandas. Write a one-paragraph "data quality report": how many rows, how many NaNs per column, what percentage of rows are complete, and what your cleaning strategy would be for each column with NaN.

Key Takeaways

  • Find NaN with df.isna().sum(); find duplicates with df.duplicated().sum().
  • Three NaN strategies: drop, fill, leave alone. Choose based on % missing and column importance.
  • Always inspect duplicates before dropping — they might be legitimate.
  • Clean text (strip, title-case) before grouping or joining.
  • Convert text-stored numbers with pd.to_numeric(..., errors="coerce").
Course continuity
Previously learned: Lesson 26 covered filtering, sorting, grouping.
Today: You learned to clean data — the unglamorous but essential step before any analysis.
Next: Lesson 28 adds visualization — turning clean DataFrames into charts with pandas and matplotlib.

FAQ

What is the difference between None, np.nan, and pd.NA?

None is Python's general "no value". np.nan is a special float value used by NumPy/pandas for missing numeric data. pd.NA is pandas' newer, type-agnostic missing value indicator. In practice, np.nan is what you will see most often in numeric columns, and pandas treats them all similarly through isna().

Should I fill NaN before or after splitting train/test data in ML?

Always compute the fill value (mean, median) on the training data only, then apply it to both train and test. Otherwise you leak information from test into training. For pure analytics, this matters less, but the principle is the same: compute statistics on the data you have at decision time.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments