Course: Basic Data Transformation
Module: 7 of 8
Level: Beginner
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.
Missing data refers to information that should be available in a dataset but is not recorded.
Consider this school record:
| Name | Age | Class | Score |
|---|---|---|---|
| Tunde | 13 | JSS 2 | 85 |
| Amina | 12 | JSS 1 | 90 |
| David | 14 | JSS 3 | |
| Grace | 13 | JSS 2 | 78 |
David's examination score is missing. The school has recorded his name, age, and class but has not entered his score.
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:
Duplicate data occurs when the same record appears more than once in a dataset.
Consider this example:
| Student ID | Name | Score |
|---|---|---|
| 101 | Tunde | 85 |
| 102 | Amina | 90 |
| 103 | David | 75 |
| 101 | Tunde | 85 |
The record for Tunde appears twice. If the school counts both records, it may incorrectly believe that four different students took the examination.
Duplicate records can cause several problems:
Python has tools that help us find missing information. When using Pandas, missing values are commonly represented by NaN or other missing-value markers.
import pandas as pd
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.
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.
print(df.isnull().sum())
This helps us count how many missing values appear in each column.
There are different ways to handle missing information. The correct method depends on the type of data and why the information is missing.
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.
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.
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.
Pandas provides a function called duplicated() to identify repeated records.
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)
print(df.duplicated())
The duplicated() function checks for repeated rows. By default, it marks later occurrences as duplicates.
print(df.duplicated().sum())
This counts the number of duplicate rows.
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.
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.
You do not need Python to find missing or duplicate information. Spreadsheet applications also provide useful tools.
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]
}
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:
| ID | Name | Score |
|---|---|---|
| 201 | Chika | 88 |
| 202 | Samuel | 76 |
| 203 | Grace | Missing |
| 204 | Tunde | 82 |
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.
A missing value does not always mean zero. Check the original source before deciding what to do.
Do not remove incomplete records without considering how this could affect your analysis.
Two students may have the same name. Use a reliable identifier such as student ID before deciding that records are duplicates.
Always inspect your cleaned dataset to make sure important information has not been removed or changed incorrectly.
| Term | Meaning |
|---|---|
| Missing Data | Information that is not available in a dataset. |
| Duplicate Data | Records that appear more than once. |
| Data Cleaning | Finding and correcting problems in a dataset. |
| NaN | A 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 Imputation | Filling missing numerical values using the average. |
In this module, you learned how to identify and handle missing and duplicate information.
You learned how to:
Answer all 10 questions to check what you have learned.
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.