Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Phyton For Data Cleaning Β· 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: Python for Data Cleaning – Handling Missing Values

πŸ“˜ Module Three: Python for Data Cleaning – Handling Missing Values

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!

🎯 Learning Objectives

After this module, you will be able to:

  • Identify and count missing values in a dataset.
  • Decide whether to drop or fill missing values.
  • Use dropna() to remove rows with missing values.
  • Use fillna() to fill missing values with a specific value.
  • Use interpolation to fill missing values logically.
  • Apply these techniques to real datasets.

πŸ“– Warm-up Story: The Incomplete Survey

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.

πŸ“š Main Lessons

Lesson 1: What are Missing Values?

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.

Lesson 2: Why Missing Values Happen

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.

Lesson 3: Finding Missing Values in Pandas

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.

Lesson 4: Counting 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.

Lesson 5: The Problem with 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.

Lesson 6: Dealing with Missing Values – Drop or Fill?

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.

Lesson 7: Dropping Missing Values with dropna()

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.

Lesson 8: Filling Missing Values with fillna()

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.

Lesson 9: Filling with the Mean, Median, or Mode

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.

Lesson 10: Forward Fill and Backward Fill

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.

Lesson 11: Interpolation

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.

Lesson 12: When to Drop vs. When to Fill

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.

Lesson 13: Handling Missing Values in Categorical Data

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.

Lesson 14: Practice Cleaning Missing Values

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.

Lesson 15: Your Missing Data Project

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.

πŸ”‘ Key Vocabulary

  • Missing Values: Empty spaces in data.
  • isnull(): Finds missing values.
  • sum(): Counts missing values.
  • dropna(): Removes missing values.
  • fillna(): Fills missing values.
  • Mean: Average value.
  • Median: Middle value.
  • Mode: Most common value.
  • Forward Fill: Uses previous value.
  • Backward Fill: Uses next value.
  • Interpolation: Estimates missing values.
  • Categorical: Text or category data.

πŸ’‘ Important Concepts

  • Missing values are common.
  • Find missing values with isnull().sum().
  • Drop missing values with dropna().
  • Fill missing values with fillna().
  • Use mean, median, or mode to fill numbers.
  • Use forward/backward fill for time data.
  • Use interpolation for smooth estimates.
  • For text, fill with "Unknown" or mode.
  • Drop when little missing; fill when lots missing.

πŸ“ Step-by-Step Explanations

How to Handle Missing Values in 6 Steps:

  1. Load Data: data = pd.read_csv("file.csv")
  2. Explore Data: data.head(), data.info()
  3. Find Missing: data.isnull().sum()
  4. Decide: Will you drop or fill?
  5. Apply: data.dropna() or data.fillna(value)
  6. Validate: data.isnull().sum() again

🌍 Real-life Examples

  • A hospital fills missing patient records with "Unknown".
  • A bank drops rows with missing transaction amounts.
  • A school fills missing grades with the class average.
  • A company fills missing customer emails with "none@example.com".

πŸ‡³πŸ‡¬ Nigerian Examples

  • A Nigerian bank fills missing customer addresses with "Unknown".
  • A Nigerian school fills missing attendance with the previous day.
  • A Nigerian farmer uses interpolation to fill missing crop data.
  • A Nigerian business drops rows with missing product details.

🎈 Fun Examples Children Relate To

  • Missing values are like missing pieces in a puzzle.
  • Filling missing values is like drawing in the missing parts of a picture.
  • Dropping missing values is like removing a damaged puzzle piece.
  • Using the average is like guessing a missing number.

🏠 Everyday Examples

  • If you missed a day in your journal, you might leave it blank or fill it with "no entry".
  • If you don't know the exact amount of a receipt, you might estimate it.
  • If you forget to write a task on your to-do list, you might add it later.
  • If you don't know the exact date of an event, you might use "unknown".

πŸ§‘β€πŸ« Teacher Notes

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.

πŸ‘ͺ Parent Tips

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.

🌟 Interesting Facts

  • Missing values are also called null values, NA (not available), or NaN (not a number).
  • In some datasets, up to 50% of the data can be missing.
  • Many machine learning algorithms cannot handle missing values, so you must clean them first.
  • Interpolation is often used in weather forecasting.

πŸ€” Did You Know?

  • Did you know that missing values can be intentionally left blank to represent "not applicable"?
  • Did you know that some data analysts use "NULL" to represent missing values?
  • Did you know that Pandas uses NaN to represent missing values?
  • Did you know that missing data can be predicted using machine learning?

🧠 Remember This

  • Missing values are empty spaces in data.
  • Find them with isnull().sum().
  • Drop them with dropna().
  • Fill them with fillna().
  • Use mean, median, mode for numbers.
  • Use forward/backward fill for time data.
  • Use interpolation for smooth estimates.
  • For text, fill with "Unknown" or mode.
  • Drop when little missing; fill when lots missing.

❌ Common Mistakes

  • Not checking for missing values: Always check first.
  • Dropping too much data: Don't drop if many rows are missing.
  • Filling with the wrong value: Use appropriate values.
  • Using mean for text data: You can't use mean on text.
  • Not validating: Always check that missing values are fixed.
  • Ignoring the reason for missing data: Understanding why helps choose the right method.

βœ… Best Practices

  • Always check for missing values first.
  • Understand why data is missing.
  • Drop only when few rows are missing.
  • Fill with appropriate values (mean, median, mode).
  • Use forward/backward fill for time series.
  • Use interpolation for smooth data.
  • For text, use "Unknown" or mode.
  • Always validate after cleaning.
  • Document your approach.

πŸ“Š Clear ASCII Illustrations

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
    

πŸ“‹ Comparison Tables

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

πŸ“Œ End-of-Module Summary

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!

❓ Frequently Asked Questions

  1. What are missing values? Empty spaces in data.
  2. How do you find missing values? Use data.isnull().sum().
  3. What does dropna() do? Removes rows with missing values.
  4. What does fillna() do? Fills missing values with a value.
  5. What is mean? The average value.
  6. What is median? The middle value.
  7. What is mode? The most common value.
  8. What is forward fill? Uses the previous value.
  9. What is interpolation? Estimates missing values.
  10. When should you drop vs. fill? Drop when little missing; fill when lots missing.

πŸ“ Review Questions

  1. What are missing values?
  2. How do you find missing values in Pandas?
  3. What does dropna() do?
  4. What does fillna() do?
  5. What is the mean?
  6. What is the median?
  7. What is the mode?
  8. What is forward fill?
  9. What is interpolation?
  10. When should you drop missing values?
  11. When should you fill missing values?
  12. How do you fill missing values in categorical data?
  13. What is the first step in handling missing values?
  14. Why is it important to validate after cleaning?
  15. Give a Nigerian example of handling missing values.

✍️ Fill-in-the-Blank

  1. ______ are empty spaces in data. (Missing values)
  2. Use ______ to find missing values. (isnull().sum())
  3. ______ removes rows with missing values. (dropna())
  4. ______ fills missing values with a value. (fillna())
  5. The ______ is the average value. (mean)
  6. The ______ is the middle value. (median)
  7. The ______ is the most common value. (mode)
  8. ______ uses the previous value to fill a missing value. (Forward fill)
  9. ______ estimates missing values smoothly. (Interpolation)
  10. For categorical data, fill with ______. (Unknown or mode)

βœ… True or False

  1. Missing values are not a problem. (False)
  2. isnull().sum() counts missing values. (True)
  3. dropna() removes all missing values. (True)
  4. fillna() cannot be used for text data. (False)
  5. The mean is the middle value. (False)
  6. The mode is the most common value. (True)
  7. Forward fill uses the next value. (False)
  8. Interpolation is used for smooth data. (True)
  9. You should always drop missing values. (False)
  10. You should always validate after cleaning. (True)

πŸ”˜ Multiple Choice Questions

  1. What are missing values?
    A) Extra data
    B) Empty spaces in data
    C) Duplicate data
    D) Correct data
    Answer: B
  2. How do you find missing values?
    A) data.count()
    B) data.isnull().sum()
    C) data.missing()
    D) data.empty()
    Answer: B
  3. What does dropna() do?
    A) Removes missing values
    B) Fills missing values
    C) Counts missing values
    D) Finds missing values
    Answer: A
  4. What does fillna() do?
    A) Removes missing values
    B) Fills missing values
    C) Counts missing values
    D) Finds missing values
    Answer: B
  5. What is the mean?
    A) Middle value
    B) Most common value
    C) Average value
    D) Largest value
    Answer: C
  6. What is the median?
    A) Average value
    B) Middle value
    C) Most common value
    D) Largest value
    Answer: B
  7. What is the mode?
    A) Average value
    B) Middle value
    C) Most common value
    D) Largest value
    Answer: C
  8. What is forward fill?
    A) Uses the next value
    B) Uses the previous value
    C) Uses the average
    D) Uses the median
    Answer: B
  9. What is interpolation?
    A) Removes missing values
    B) Estimates missing values
    C) Counts missing values
    D) Fills with a constant
    Answer: B
  10. When should you drop missing values?
    A) When many are missing
    B) When few are missing
    C) When data is categorical
    D) When data is numerical
    Answer: B
  11. When should you fill missing values?
    A) When few are missing
    B) When many are missing
    C) When data is categorical
    D) When data is numerical
    Answer: B
  12. How do you fill missing values in categorical data?
    A) With mean
    B) With median
    C) With mode or "Unknown"
    D) With interpolation
    Answer: C
  13. What is the first step in handling missing values?
    A) Fill them
    B) Drop them
    C) Find and count them
    D) Ignore them
    Answer: C
  14. Why validate after cleaning?
    A) To make sure it's done
    B) To check if missing values are fixed
    C) To delete data
    D) To add more missing values
    Answer: B
  15. Which is a Nigerian example of handling missing values?
    A) Filling missing rainfall data
    B) Dropping missing student records
    C) Both A and B
    D) Neither A nor B
    Answer: C

πŸ”— Matching Exercises

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

✏️ Short Answer Questions

  1. What are missing values?
  2. How do you count missing values?
  3. What is the difference between dropna() and fillna()?
  4. When would you use forward fill?
  5. Give a Nigerian example of using interpolation.

🎭 Scenario-based Exercises

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?

πŸ‘₯ Group Activity

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.

πŸ§‘ Individual Activity

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.

πŸ’¬ Classroom Discussion Questions

  • Why is it important to handle missing values?
  • What are some challenges in handling missing values?
  • When would you choose to drop missing values?
  • When would you choose to fill missing values?
  • How can Nigerian businesses benefit from handling missing values?

πŸ› οΈ Mini Project

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().

πŸ“„ Practical Assignment

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.

πŸ† Challenge Exercise

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.

πŸ” Quiz Answers

Answers to the Multiple Choice Questions are already provided above. For other exercises, refer to the lessons and key vocabulary.

🎁 Key Takeaways

  • Missing values are empty spaces in data.
  • Find missing values with isnull().sum().
  • Drop missing values with dropna().
  • Fill missing values with fillna().
  • Use mean, median, mode for numbers.
  • Use forward/backward fill for time data.
  • Use interpolation for smooth estimates.
  • For text, fill with "Unknown" or mode.
  • Drop when little missing; fill when lots missing.

πŸ”œ Preparation for Module Four

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!

πŸ† 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.
β†’