Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to Data Science ยท Lesson 4 of 9

Module Three

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
4
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

Duration: 1 Week (approx. 4โ€“6 hours of study + 2 hours lab)

Format: Lectures, readings, discussion, and a hands-on lab

Prerequisites: Modules 1 and 2

Learning Materials: This module, a computer with Python (Google Colab works), and a notebook

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

  1. Download a deliberately messy dataset (e.g., the "Titanic" dataset from Kaggle, or a sample with injected errors).
  2. Open it in a Jupyter Notebook or Google Colab.
  3. 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?
  4. 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.
  5. Write a data cleaning log documenting each step.
  6. 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

  1. Why is data cleaning often called the "unglamorous 80%" of data science?
  2. What's the danger of dropping rows with missing data? Can you think of a scenario where it would bias results?
  3. When should you investigate an outlier rather than delete it?
  4. Why is documenting cleaning decisions so important? What could go wrong if you skip it?
  5. 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.

© 2026 Introduction to Data Science โ€” Module 3

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’