Module 3: Data Cleaning and Wrangling
Module 3: Data Cleaning and Wrangling
Introduction to Data Science โ Week 3
Turning messy, real-world data into clean, analysis-ready data
Module Overview
In the real world, data is almost never clean. It has missing values, duplicates, typos,
inconsistent formats, and outliers. Data cleaning and wrangling โ often the most
time-consuming part of a data science project โ is the process of transforming raw data
into a form suitable for analysis. This module covers the most common data quality issues,
strategies for handling them, and hands-on practice with pandas.
Learning Objectives
By the end of this module, students will be able to:
- Identify the most common data quality issues in real datasets.
- Choose appropriate strategies for handling missing values.
- Detect and remove duplicates and outliers.
- Standardize inconsistent text and data types.
- Use pandas to clean and reshape a messy dataset.
- Document cleaning decisions for reproducibility and transparency.
Lesson 1: Why Data Cleaning Matters
Data scientists often spend 60โ80% of their time cleaning and preparing
data. It's not glamorous, but it's essential: garbage in, garbage out. A model
trained on dirty data will produce unreliable results, no matter how sophisticated the
algorithm.
๐ณ Think of it like cooking: You wouldn't cook with unwashed vegetables or
expired ingredients. Cleaning data is the same โ you're preparing your ingredients before
you "cook" (analyze) them. Skip this step, and the final dish will be ruined.
Real-World Consequences of Dirty Data
- A hospital's readmission model performs poorly because missing patient records were silently dropped.
- A marketing campaign targets the wrong customers because of duplicated records.
- A financial report shows inflated revenue because refunds were recorded as sales.
๐ก Key Idea: Cleaning is not optional. It's the foundation of every trustworthy
analysis.
Lesson 2: The Six Common Data Quality Issues
Most messy data has one or more of these problems:
1. Missing Values ๐ณ๏ธ
Cells that should contain data but are empty.
Example: A survey respondent skipped the "income" question.
2. Duplicates ๐ฏ
The same record appears more than once.
Example: A customer signs up twice with different email addresses.
3. Inconsistent Formatting โ๏ธ
The same value is written in different ways.
Example: "USA", "U.S.A.", "United States", and "us" in a country column.
4. Typos and Invalid Values ๐ซ
Values that are clearly wrong.
Example: An age of "113" for a 13-year-old; a date of "February 30."
5. Outliers ๐ฏ
Values that are unusually far from the rest of the data.
Example: An income of $10,000,000 in a dataset of average salaries โ could be real, could be a typo.
6. Wrong Data Types ๐ข
Numbers stored as text, dates stored as strings, etc.
Example: A price column that contains "1,299" (with a comma) can't be summed until it's cleaned.
โ ๏ธ Watch Out! Not all outliers are mistakes. A $10M income could be a real
billionaire โ or a data entry error. Always investigate before deleting.
Lesson 3: Handling Missing Values
There's no single "right" way to handle missing values. The choice depends on why
the data is missing and how much is missing.
| Strategy |
When to Use |
Risks |
| Drop the row |
Very few missing values; the row isn't critical |
Loses information; can introduce bias if missingness isn't random |
| Drop the column |
The column is mostly missing or irrelevant |
May lose important information |
| Fill with a constant |
Missing means "none" or "unknown" |
Can distort distributions |
| Fill with the mean / median / mode |
You want to preserve the dataset size |
Reduces variance; can hide patterns |
| Predict / impute |
Missing values follow a pattern |
Complex; can introduce new errors |
| Leave as missing |
Missingness itself is informative |
Many tools require handling before analysis |
๐งฉ Think of it like a puzzle: If a piece is missing, you have four options:
skip that part of the picture (drop the row), fill it with a similar-looking piece (impute),
mark it as missing (leave it), or throw away the whole area (drop the column). The right choice
depends on how important that piece is.
๐ก Key Idea: Understand why data is missing before deciding how to
handle it. Missing at random is very different from missing because the value is sensitive
(e.g., income).
Lesson 4: Cleaning with pandas
pandas is the standard Python library for data cleaning. Here are the most useful commands:
Load and Inspect
import pandas as pd
data = pd.read_csv("messy_data.csv")
print(data.head()) # First 5 rows
print(data.info()) # Data types and non-null counts
print(data.describe()) # Summary statistics
print(data.isnull().sum()) # Count missing values per column
Handle Missing Values
# Drop rows with ANY missing value
data.dropna(inplace=True)
# Drop rows missing a specific column
data.dropna(subset=["income"], inplace=True)
# Fill missing values with the mean of the column
data["income"].fillna(data["income"].mean(), inplace=True)
# Fill missing categorical values with "Unknown"
data["country"].fillna("Unknown", inplace=True)
Remove Duplicates
data.drop_duplicates(inplace=True)
Standardize Text
data["country"] = data["country"].str.strip().str.lower()
data["country"] = data["country"].replace({"u.s.a.": "usa", "united states": "usa"})
Fix Data Types
data["price"] = data["price"].str.replace(",", "").astype(float)
data["date"] = pd.to_datetime(data["date"])
Handle Outliers
# Find outliers using the interquartile range (IQR) method
Q1 = data["income"].quantile(0.25)
Q3 = data["income"].quantile(0.75)
IQR = Q3 - Q1
lower = Q1 - 1.5 * IQR
upper = Q3 + 1.5 * IQR
# Filter out rows outside this range
data = data[(data["income"] >= lower) & (data["income"] <= upper)]
๐ก Pro Tip: Always work on a copy of your original data
(e.g., data_clean = data.copy()). That way, if you make a mistake, you can
always go back.
Lesson 5: Documenting Cleaning Decisions
Every cleaning decision should be documented โ for your future self, for collaborators, and
for anyone who needs to trust your results. This is sometimes called a
data cleaning log.
What to Document
- What was changed (e.g., "Filled missing income values with the column median").
- Why it was changed (e.g., "Income was missing for 12% of rows; dropping them would bias results").
- How many rows/columns were affected.
- Any assumptions made (e.g., "Assumed 'unknown' in country column means 'not collected'").
๐ Think of it like a lab notebook: Scientists record every step of an
experiment. Data scientists should do the same โ a clean log makes your work reproducible
and credible.
โ ๏ธ Warning: Never delete data without documenting why. A cleaning step that
seems harmless later may turn out to be the reason your model fails on new data.
Hands-On Lab: Clean a Messy Dataset
Goal: Practice identifying and fixing real data quality issues using pandas.
Instructions
- Download a deliberately messy dataset (e.g., the "Titanic" dataset from Kaggle, or a sample with injected errors).
- Open it in a Jupyter Notebook or Google Colab.
- Inspect the data:
- How many rows and columns? What are the data types?
- How many missing values in each column?
- Are there duplicates?
- Are there any outliers or invalid values?
- Clean the data by:
- Handling missing values (document your choice).
- Removing duplicates.
- Standardizing inconsistent text.
- Fixing data types.
- Investigating outliers โ decide whether to remove, keep, or flag them.
- Write a data cleaning log documenting each step.
- Save the cleaned dataset as a new CSV file.
Submission
Your cleaned CSV file + a one-page cleaning log describing every change you made and why.
Assessment for Module 3
- Quiz (10 questions): Covers common data quality issues, handling strategies, and pandas commands.
- Lab: Graded on completeness, correctness, and quality of documentation.
- Participation: Contribution to the group activity and discussion prompts.
Key Terms
- Data cleaning โ fixing or removing incorrect, incomplete, or irrelevant data.
- Data wrangling โ transforming and reshaping data into a usable form.
- Missing value โ a cell where data should be but isn't.
- Duplicate โ a record that appears more than once.
- Outlier โ a value that is unusually far from the rest.
- Imputation โ filling in missing values based on other data.
- IQR (interquartile range) โ a method for detecting outliers.
- Data type โ the kind of value stored in a column (number, text, date, etc.).
- Cleaning log โ a written record of all cleaning decisions.
- Reproducibility โ the ability for others to repeat your work and get the same results.
Discussion Prompts
- Why is data cleaning often called the "unglamorous 80%" of data science?
- What's the danger of dropping rows with missing data? Can you think of a scenario where it would bias results?
- When should you investigate an outlier rather than delete it?
- Why is documenting cleaning decisions so important? What could go wrong if you skip it?
- Can you think of a real-world example where poor data cleaning led to a bad decision?
Further Reading
- Wes McKinney, Python for Data Analysis โ chapters on data cleaning and preparation
- pandas official documentation โ "Working with missing data"
- Kaggle Learn: "Data Cleaning" (free micro-course)
- Hadley Wickham, "Tidy Data" paper โ a foundational framework for data structure
๐ก Instructor Note: This is often the module where students get the most
hands-on value. Use a messy dataset with injected errors (duplicates, missing values, typos)
so students experience the frustration and satisfaction of cleaning. Emphasize that
documenting decisions is part of the work, not an afterthought.