Welcome to Module Three! In the first two modules, we learned about data cleaning and how to explore data with Pandas. Now, we will tackle one of the most common problems in data cleaningβmissing values. Missing values are like empty spaces in your data. They can cause problems if not handled properly. In this module, you will learn how to find, count, and fix missing values using Python. By the end, you will be able to clean datasets that have missing information. Let's get started!
After this module, you will be able to:
A school in Nigeria conducted a survey about students' favorite subjects. But some students didn't answer all the questions. Some left the age field blank. Others didn't say their favorite subject. The school principal wanted to know the top subject, but the missing answers made it hard.
A data analyst used Python to fix the problem. First, she found all the missing values. Then, she filled in the missing ages with the average age of the class. She dropped the rows where the favorite subject was missing because there were only a few. Now the data was clean, and she could see that Mathematics was the most popular subject.
This module will teach you how to handle missing values just like that analyst.
Definition: Missing values are empty or null values in a dataset. They are like blank spaces on a form.
Why it is important: Missing values can make your analysis wrong. You need to fix them before using the data.
Simple explanation: Imagine a class register where some students' names are missing. You can't know how many students are in the class.
Real-life example: A customer's phone number is missing in a database.
School example: A student forgot to write their age on a form.
Home example: You forgot to write down one expense in your budget.
Nigerian example: A farmer forgot to record rainfall on one day.
Illustration:
+---------+---------+
| Name | Age |
+---------+---------+
| Chidi | 12 |
| Ama | |
| Bola | 13 |
+---------+---------+
Mini summary: Missing values are empty spaces in data.
Definition: Missing values happen for many reasonsβpeople forget, data isn't collected, or there are errors.
Why it is important: Understanding why data is missing helps you decide how to fix it.
Simple explanation: Sometimes people skip questions. Sometimes data is lost.
Real-life example: A customer didn't provide their email address.
School example: A student didn't answer a question on a survey.
Home example: You forgot to record a receipt.
Nigerian example: A bank may have missing data due to system errors.
Illustration:
Reasons for Missing Values:
1. People skip questions.
2. Data entry errors.
3. System failures.
4. Not applicable.
Mini summary: Missing values happen for various reasons.
Definition: You use Pandas functions like isnull() and notnull() to find missing values.
Why it is important: You need to know where the missing values are.
Simple explanation: isnull() shows True for missing values and False for non-missing.
Real-life example: A data analyst uses isnull() to find empty fields.
School example: A student uses isnull() to check for missing grades.
Home example: You use isnull() to find missing expenses.
Nigerian example: A business uses isnull() to find missing customer data.
Illustration:
data.isnull()
Mini summary: isnull() helps find missing values.
Definition: You can count missing values using isnull().sum().
Why it is important: Counting helps you understand how much data is missing.
Simple explanation: isnull().sum() counts the missing values in each column.
Real-life example: An analyst counts missing customer emails.
School example: A student counts missing test scores.
Home example: You count missing expenses.
Nigerian example: A business counts missing transaction data.
Illustration:
data.isnull().sum()
Mini summary: isnull().sum() counts missing values.
Definition: Missing values can cause errors in calculations and lead to wrong conclusions.
Why it is important: If you ignore missing values, your analysis might be wrong.
Simple explanation: If you calculate the average age and some ages are missing, the average will be wrong.
Real-life example: A company might target the wrong customers.
School example: A teacher might think students are doing well when they are not.
Home example: You might think you spent less money than you actually did.
Nigerian example: A government might plan for the wrong population.
Illustration:
Dirty Data -> Wrong Analysis -> Bad Decisions
Mini summary: Missing values lead to wrong conclusions.
Definition: You can either drop (remove) missing values or fill (replace) them with a value.
Why it is important: The choice depends on the data and the problem.
Simple explanation: If only a few rows are missing, you can drop them. If many rows are missing, you might want to fill them.
Real-life example: If a customer is missing an email, you might fill it with a default.
School example: If a student is missing a grade, you might fill it with the class average.
Home example: If you missed a receipt, you might estimate the amount.
Nigerian example: If a farmer missed a day of rainfall, you might fill it with an average.
Illustration:
Missing Values -> Drop or Fill?
Mini summary: Decide whether to drop or fill missing values.
Definition: dropna() removes rows or columns that have missing values.
Why it is important: It's a quick way to clean data when there are few missing values.
Simple explanation: If a row has any missing value, it is deleted.
Real-life example: A data analyst drops rows with missing customer emails.
School example: A student drops rows with missing grades.
Home example: You drop missing expenses from your budget.
Nigerian example: A business drops rows with missing transaction details.
Illustration:
data.dropna()
Mini summary: dropna() removes rows with missing values.
Definition: fillna() replaces missing values with a specified value.
Why it is important: It allows you to keep all the data and still fix missing values.
Simple explanation: You replace missing values with a number, a text, or an average.
Real-life example: You fill missing customer emails with "unknown@email.com".
School example: You fill missing grades with the class average.
Home example: You fill missing expenses with 0.
Nigerian example: You fill missing crop data with last year's average.
Illustration:
data.fillna(0)
Mini summary: fillna() replaces missing values with a value.
Definition: You can fill missing values with the mean (average), median (middle value), or mode (most common value).
Why it is important: These are logical ways to fill missing numbers.
Simple explanation: If you know the average age, you can fill missing ages with that average.
Real-life example: A company fills missing salaries with the median salary.
School example: You fill missing test scores with the class average.
Home example: You fill missing grocery costs with the average.
Nigerian example: A farmer fills missing rainfall data with the monthly average.
Illustration:
data.fillna(data.mean())
Mini summary: Use mean, median, or mode to fill missing values.
Definition: Forward fill (ffill) uses the previous value to fill a missing value. Backward fill (bfill) uses the next value.
Why it is important: Useful for time series data where the next or previous value makes sense.
Simple explanation: If Monday's data is missing, you use Sunday's data.
Real-life example: Stock prices are often filled using forward fill.
School example: If attendance is missing for one day, you use the previous day.
Home example: If you missed a daily expense, you use the previous day's expense.
Nigerian example: A farmer uses forward fill for missing daily temperature data.
Illustration:
data.fillna(method='ffill')
Mini summary: Forward and backward fill use neighboring values.
Definition: Interpolation estimates missing values based on the values around them.
Why it is important: It creates a smooth estimate for missing data.
Simple explanation: If you have points on a line, interpolation fills the missing point on the line.
Real-life example: Scientists use interpolation to fill missing climate data.
School example: You can interpolate missing scores based on previous and next scores.
Home example: You can interpolate missing temperatures.
Nigerian example: A farmer uses interpolation to estimate missing crop growth data.
Illustration:
data.interpolate()
Mini summary: Interpolation estimates missing values smoothly.
Definition: You drop when missing data is very little. You fill when missing data is significant.
Why it is important: The wrong choice can affect your analysis.
Simple explanation: If 1% of data is missing, drop it. If 20% is missing, fill it.
Real-life example: A company drops less than 5% missing data and fills more than that.
School example: A teacher drops a few missing grades but fills many.
Home example: You drop missing receipts that are few, but fill missing expenses that are many.
Nigerian example: A business drops a few missing records but fills many to keep the dataset.
Illustration:
Little Missing -> Drop
Lots Missing -> Fill
Mini summary: Drop when little is missing; fill when much is missing.
Definition: Categorical data is text data, like "city" or "gender".
Why it is important: You can't use mean for text. You can use mode or fill with "Unknown".
Simple explanation: If the city is missing, fill it with "Unknown" or the most common city.
Real-life example: A company fills missing customer city with "Unknown".
School example: A student fills missing subject with "Unknown".
Home example: You fill missing item category with "Other".
Nigerian example: A business fills missing region with "Unknown".
Illustration:
data['city'].fillna('Unknown')
Mini summary: Fill categorical missing values with "Unknown" or mode.
Definition: Practice applying all the techniques you learned.
Why it is important: Practice helps you remember and build skills.
Simple explanation: You take a messy dataset and fix all missing values.
Real-life example: A data analyst practices on a sample dataset.
School example: A student works on a class exercise.
Home example: You practice on your own expense data.
Nigerian example: A Nigerian student uses local data for practice.
Illustration:
data.dropna()
data.fillna(value)
data.fillna(data.mean())
data.fillna(method='ffill')
data.interpolate()
Mini summary: Practice all techniques to master missing values.
Definition: A project where you apply all missing value techniques to a real dataset.
Why it is important: It gives you real-world experience.
Simple explanation: You find a dataset, explore it, find missing values, and fix them.
Real-life example: A data analyst cleans a customer dataset.
School example: A student completes a class project.
Home example: You clean your family's expense data.
Nigerian example: A student uses a Nigerian dataset for the project.
Illustration:
Step 1: Load data.
Step 2: Explore data.
Step 3: Find missing values.
Step 4: Decide to drop or fill.
Step 5: Apply the chosen method.
Step 6: Validate the cleaned data.
Mini summary: Apply missing value techniques to a real dataset.
How to Handle Missing Values in 6 Steps:
This module is critical for data cleaning. Teachers should emphasize that handling missing values is a decision-making process. Encourage students to think about why data is missing and what method is best. Use real datasets with missing values. Have students practice dropping, filling with mean, forward fill, and interpolation. Discuss the pros and cons of each method.
Parents can help children understand missing values by using everyday examples. For instance, "If we don't know the price of one item, we can guess based on similar items." Encourage children to think about how they deal with missing information in daily life.
Missing Value Handling Flowchart
Missing Values -> Check -> Drop or Fill?
-> Drop: dropna() -> Clean Data
-> Fill: fillna() -> Clean Data
Forward Fill Example
Original: 10, 20, NaN, 40
Forward Fill: 10, 20, 20, 40
Drop vs Fill
| Drop | Fill |
|---|---|
| Removes rows. | Keeps rows. |
| Good when few missing. | Good when many missing. |
| Loses data. | Keeps data. |
Fill Methods
| Method | When to Use |
|---|---|
| Mean | Numerical data with normal distribution |
| Median | Numerical data with outliers |
| Mode | Categorical data |
| Forward Fill | Time series data |
| Interpolation | Smooth continuous data |
In Module Three, we learned how to handle missing values in Python using Pandas. We learned to find and count missing values with isnull().sum(). We explored two main approaches: dropping missing values with dropna() and filling them with fillna(). We filled using mean, median, mode, forward/backward fill, and interpolation. We also discussed how to handle categorical data and when to drop vs. fill. These skills are essential for cleaning real-world datasets. You are now ready to fix missing values in any dataset!
Match the term with its description:
| Term | Description |
|---|---|
| 1. isnull() | A. Removes missing values |
| 2. dropna() | B. Fills missing values |
| 3. fillna() | C. Finds missing values |
| 4. Mean | D. Most common value |
| 5. Mode | E. Average value |
Answers: 1-C, 2-A, 3-B, 4-E, 5-D
Scenario 1: You have a dataset of student grades. Some grades are missing. What would you do? Explain your steps.
Scenario 2: A company's customer data has missing emails for 60% of customers. What would you do?
Scenario 3: A farmer has daily rainfall data with some missing days. How would you fill the missing days?
In groups, get a dataset with missing values (from Kaggle or data.gov.ng). Each group member uses a different method to handle missing values (drop, fill with mean, forward fill, interpolation). Compare the results and discuss which method worked best.
Create a small dataset with missing values. Write Python code to handle the missing values using at least three different methods. Compare the results and write a short reflection on your choice.
Create a "Missing Values Report" for a dataset of your choice. Include: the number of missing values per column, your chosen method to handle them, and the cleaned data. Show before and after using head() and info().
Download a dataset with missing values (e.g., from data.gov.ng). Handle all missing values using appropriate methods. Write a report explaining your choices and show the cleaned dataset.
Find a dataset with missing values in both numerical and categorical columns. Use different methods for each type. Write a Python script that automates the handling of missing values.
Answers to the Multiple Choice Questions are already provided above. For other exercises, refer to the lessons and key vocabulary.
In Module Four, we will learn how to handle duplicate data, inconsistent formatting, and outliers. These are the next steps in cleaning messy data. Get ready to become a data cleaning expert!
End of Module Three β You are now a missing values master!