Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Basic Data Transformation ยท Lesson 8 of 9

Module Seven

๐Ÿ“– 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.
8
Module 7: Handling Missing and Duplicate Data

MODULE 7: HANDLING MISSING AND DUPLICATE DATA

Course: Basic Data Transformation

Module: 7 of 8

Level: Beginner

1. Introduction

Imagine that you are helping a school administrator organise student records. The school has a spreadsheet containing students' names, ages, classes, and examination scores.

While checking the spreadsheet, you discover that some students have no recorded scores. You also notice that one student's name appears twice.

What should you do?

You need to identify the missing information and investigate the repeated records before using the data.

This process is called data cleaning.

In this module, you will learn how to identify missing data, find duplicates, and prepare information for accurate analysis.

2. What Is Missing Data?

Missing data refers to information that should be available in a dataset but is not recorded.

Consider this school record:

Name Age Class Score
Tunde13JSS 285
Amina12JSS 190
David14JSS 3
Grace13JSS 278

David's examination score is missing. The school has recorded his name, age, and class but has not entered his score.

Common Reasons for Missing Data

  • A person forgot to enter the information.
  • A computer system failed to save a record.
  • A student did not provide the required information.
  • Information was lost during data transfer.
  • A form was submitted without all the required fields.
  • Two systems did not exchange all their information correctly.

3. Why Is Missing Data a Problem?

Missing information can affect the quality of your analysis.

For example, imagine these examination scores:

80, 90, 70, Missing

If you want to calculate the average score, you cannot simply treat the missing value as a real examination score.

Missing data can:

  • Make calculations incomplete.
  • Produce misleading reports.
  • Make it difficult to compare records.
  • Reduce the accuracy of data analysis.
  • Make decision-making more difficult.

4. What Is Duplicate Data?

Duplicate data occurs when the same record appears more than once in a dataset.

Consider this example:

Student IDNameScore
101Tunde85
102Amina90
103David75
101Tunde85

The record for Tunde appears twice. If the school counts both records, it may incorrectly believe that four different students took the examination.

Common Causes of Duplicate Data

  • A user submits the same form more than once.
  • Records are imported into a system multiple times.
  • Two departments enter the same information.
  • A computer system repeats a transaction.
  • Data is copied and pasted incorrectly.

5. Why Should We Remove Duplicate Records?

Duplicate records can cause several problems:

  • Incorrect calculations.
  • Wrong customer or student counts.
  • Repeated payments or transactions in reports.
  • Confusing information.
  • Unreliable business decisions.
Important: Do not automatically delete every record that looks similar. Two people may have the same name but be different people. Always use reliable identifying information, such as a unique student ID or customer ID.

6. Identifying Missing Data in Python

Python has tools that help us find missing information. When using Pandas, missing values are commonly represented by NaN or other missing-value markers.

Step 1: Import Pandas

import pandas as pd

Step 2: Create a Dataset

import pandas as pd

students = {
    "Name": ["Tunde", "Amina", "David", "Grace"],
    "Score": [85, 90, None, 78]
}

df = pd.DataFrame(students)

print(df)

Expected output:

    Name  Score
0  Tunde   85.0
1  Amina   90.0
2  David    NaN
3  Grace   78.0

The value NaN indicates that David's score is missing.

Step 3: Find Missing Values

print(df.isnull())

The isnull() function checks each cell and identifies missing values. It returns True when a value is missing and False when a value is present.

Step 4: Count Missing Values

print(df.isnull().sum())

This helps us count how many missing values appear in each column.

7. How to Handle Missing Data

There are different ways to handle missing information. The correct method depends on the type of data and why the information is missing.

A. Remove Records with Missing Values

Sometimes, you may remove rows that contain missing information. This is useful when only a small number of records are incomplete and removing them will not unfairly affect the analysis.

cleaned_data = df.dropna()

print(cleaned_data)

The dropna() function removes rows containing missing values by default.

B. Fill Missing Values with a Suitable Value

Instead of removing a record, you may fill a missing value when you have a suitable reason to do so.

Example:

df["Score"] = df["Score"].fillna(0)

print(df)

This replaces missing scores with zero. However, only use zero when it correctly represents the situation. A missing examination score does not automatically mean that the student scored zero.

C. Fill Missing Values with the Average

For some numerical datasets, the average can be used to fill missing values. This method is called mean imputation.

average_score = df["Score"].mean()

df["Score"] = df["Score"].fillna(average_score)

print(df)

The mean() function calculates the average of the available scores.

Remember: Do not guess missing information. For example, do not invent a student's examination score. Ask for the original record or use an appropriate documented method.

8. Finding Duplicate Records in Python

Pandas provides a function called duplicated() to identify repeated records.

Step 1: Create a Dataset with Duplicates

import pandas as pd

students = {
    "ID": [101, 102, 103, 101],
    "Name": ["Tunde", "Amina", "David", "Tunde"],
    "Score": [85, 90, 75, 85]
}

df = pd.DataFrame(students)

print(df)

Step 2: Identify Duplicate Records

print(df.duplicated())

The duplicated() function checks for repeated rows. By default, it marks later occurrences as duplicates.

Step 3: Count Duplicate Records

print(df.duplicated().sum())

This counts the number of duplicate rows.

9. Removing Duplicate Records

If you have confirmed that a record is an unwanted duplicate, you can remove it using drop_duplicates().

cleaned_data = df.drop_duplicates()

print(cleaned_data)

Expected result:

    ID   Name  Score
0  101  Tunde     85
1  102  Amina     90
2  103  David     75

The repeated record has been removed.

Checking Duplicates Using One Column

You can also check for duplicate values using a particular column. For example, student ID should normally be unique.

print(df.duplicated(subset=["ID"]))

This checks whether an ID has appeared before.

10. Checking Data in Excel and Google Sheets

You do not need Python to find missing or duplicate information. Spreadsheet applications also provide useful tools.

Finding Missing Data

  1. Open your spreadsheet.
  2. Select the cells you want to inspect.
  3. Use the Find option or filtering tools.
  4. Look for blank cells.
  5. Check the original records before filling missing information.

Removing Duplicate Data in Excel

  1. Open your Excel spreadsheet.
  2. Select the table containing your records.
  3. Open the Data tab.
  4. Select Remove Duplicates.
  5. Choose the columns that identify a duplicate.
  6. Review the result before saving.

Removing Duplicates in Google Sheets

  1. Open your Google Sheets document.
  2. Select the data range.
  3. Click Data.
  4. Choose Data cleanup.
  5. Select Remove duplicates.
  6. Choose the columns to check.
  7. Review the result.

11. Practical Project: Cleaning School Records

Your Challenge

A secondary school in Ibadan has a student examination dataset. The administrator wants you to identify missing scores and remove confirmed duplicate records.

Dataset:

students = {
    "ID": [201, 202, 203, 201, 204],
    "Name": ["Chika", "Samuel", "Grace", "Chika", "Tunde"],
    "Score": [88, 76, None, 88, 82]
}

Your Tasks

  1. Create the dataset using Pandas.
  2. Display the dataset.
  3. Find the missing values.
  4. Count the missing values.
  5. Identify duplicate records.
  6. Remove the confirmed duplicate row.
  7. Display the cleaned dataset.

Complete Python Solution

import pandas as pd

students = {
    "ID": [201, 202, 203, 201, 204],
    "Name": ["Chika", "Samuel", "Grace", "Chika", "Tunde"],
    "Score": [88, 76, None, 88, 82]
}

df = pd.DataFrame(students)

print("Original Data:")
print(df)

print("\nMissing Values:")
print(df.isnull())

print("\nMissing Value Count:")
print(df.isnull().sum())

print("\nDuplicate Records:")
print(df.duplicated())

cleaned_data = df.drop_duplicates()

print("\nCleaned Data:")
print(cleaned_data)

Expected cleaned dataset:

IDNameScore
201Chika88
202Samuel76
203GraceMissing
204Tunde82

Notice that the duplicate Chika record has been removed. Grace's score is still missing because we have not yet obtained a reliable value for it.

12. Common Mistakes to Avoid

Mistake 1: Treating Every Missing Value as Zero

A missing value does not always mean zero. Check the original source before deciding what to do.

Mistake 2: Deleting Important Records

Do not remove incomplete records without considering how this could affect your analysis.

Mistake 3: Removing Different People with Similar Names

Two students may have the same name. Use a reliable identifier such as student ID before deciding that records are duplicates.

Mistake 4: Forgetting to Check the Results

Always inspect your cleaned dataset to make sure important information has not been removed or changed incorrectly.

13. Key Terms to Remember

TermMeaning
Missing DataInformation that is not available in a dataset.
Duplicate DataRecords that appear more than once.
Data CleaningFinding and correcting problems in a dataset.
NaNA common marker for a missing numerical value.
isnull()Checks for missing values in Pandas.
dropna()Removes rows or columns containing missing values.
fillna()Replaces missing values with a chosen value.
duplicated()Identifies repeated records.
drop_duplicates()Removes duplicate records.
Mean ImputationFilling missing numerical values using the average.

14. Module Summary

In this module, you learned how to identify and handle missing and duplicate information.

You learned how to:

  • Understand missing data and its causes.
  • Identify duplicate records.
  • Check for missing values using Pandas.
  • Count missing values in a dataset.
  • Remove or fill missing values appropriately.
  • Identify and remove confirmed duplicate records.
  • Clean datasets using Python, Excel, and Google Sheets.
Remember: Good data analysis starts with good-quality data. Always check your records before using them to make decisions.

15. Module Assessment: Test Your Knowledge

Answer all 10 questions to check what you have learned.

Next Module

Module 8: Introduction to Data Validation and Quality Checks

In the final module, you will learn how to check whether data is correct, complete, consistent, and suitable for use.

CRMNuggets โ€“ Learn. Practice. Get Certified.

๐Ÿ† 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.
โ†’