Imagine a supermarket in Lagos that keeps records of its daily sales. The records contain product names, prices, quantities, and dates. However, some product names are misspelled, some prices are missing, and a few records appear more than once.
Can the supermarket trust these records to make business decisions? Not completely. The data needs to be cleaned before it can be analysed.
In this module, you will learn how to use Python and Pandas to identify problems in data, correct common errors, and discover useful information.
By the end of this module, you should be able to:
Data cleaning is the process of finding and correcting errors, removing unwanted information, and making a dataset more accurate and organised.
Think about cleaning your bedroom. You arrange scattered books, remove unwanted items, and put everything in the right place. Data cleaning works in a similar way, but instead of cleaning a room, you are organising information.
Data cleaning helps us to:
For example, if a shop records the same sale five times by mistake, the calculated income may be higher than the actual income. Cleaning the data helps prevent this problem.
A missing value happens when information is not available in a cell. For example, a sales record may have a product name but no price.
Duplicate records are repeated entries in a dataset. For example, the same student may appear twice in a school results table.
This happens when information is entered wrongly. For example, a product price may be entered as โฆ50000 instead of โฆ5,000.
The same information may be written in different ways. For example, a city may appear as "Lagos", "lagos", and "LAGOS".
A number may accidentally be stored as text. This can make mathematical calculations difficult.
Let's create a small dataset containing sales records. We will deliberately include some errors so that we can practise cleaning them.
import pandas as pd
data = {
"Product": ["Rice", "Bread", "Milk", "Rice", "Sugar", None],
"Price": [5000, 1500, None, 5000, 3000, 2000],
"Quantity": [4, 10, 6, 4, None, 3],
"City": ["Lagos", "lagos", "Ibadan", "Lagos", "ABUJA", "Ibadan"]
}
sales = pd.DataFrame(data)
print(sales)
This dataset contains missing values, a duplicate record, and inconsistent city names.
Before cleaning a dataset, we need to find out where information is missing.
Use the isnull() command:
print(sales.isnull())
Pandas displays True where a value is missing and False where a value is available.
To count missing values in each column, use:
print(sales.isnull().sum())
This helps us understand how many missing values exist in each column.
There are different ways to handle missing values. The best method depends on what the missing information represents.
We can remove rows that contain missing values using
dropna().
clean_sales = sales.dropna()
print(clean_sales)
This removes every row containing at least one missing value. Be careful: important information may be lost when you remove rows.
Another method is to replace missing values with a suitable value. For example, we can fill missing prices with the average price.
sales["Price"] = sales["Price"].fillna(
sales["Price"].mean()
)
print(sales)
We can also fill missing product names with the word "Unknown".
sales["Product"] = sales["Product"].fillna("Unknown")
Important: Never replace missing values with zero automatically. A missing price does not always mean that the product is free. Choose a replacement based on what the data actually means.
Duplicate records can make reports inaccurate. Pandas provides
duplicated() to identify repeated rows.
print(sales.duplicated())
To remove duplicate rows, use:
sales = sales.drop_duplicates()
print(sales)
Pandas keeps the first occurrence by default and removes later identical rows.
Sometimes the same information is written using different capital letters or extra spaces.
For example:
We can make the text consistent using the str.title() method:
sales["City"] = sales["City"].str.strip().str.title()
print(sales["City"])
The str.strip() method removes unwanted spaces at the
beginning and end of text. The str.title() method
changes the text to title case.
Data types tell Python what kind of information is stored in a column. For example, a price should usually be stored as a number.
To check the data types in a dataset, use:
print(sales.dtypes)
To convert a column into a numeric data type, use:
sales["Price"] = pd.to_numeric(
sales["Price"], errors="coerce"
)
The errors="coerce" setting changes values that cannot
be converted into numbers into missing values. You can then decide
how to handle them.
Sorting means arranging information in a particular order. You can sort numbers from smallest to largest or names alphabetically.
Sort products by price from lowest to highest:
sorted_sales = sales.sort_values(by="Price")
print(sorted_sales)
Sort products from highest price to lowest price:
sorted_sales = sales.sort_values(
by="Price",
ascending=False
)
print(sorted_sales)
Filtering helps us display only the records that meet a particular condition.
For example, display products with a price greater than โฆ2,000:
expensive_products = sales[
sales["Price"] > 2000
]
print(expensive_products)
You can also filter products sold in Lagos:
lagos_sales = sales[
sales["City"] == "Lagos"
]
print(lagos_sales)
After cleaning our data, we can begin analysing it to discover useful information.
average_price = sales["Price"].mean()
print("Average Price:", average_price)
highest_price = sales["Price"].max()
print("Highest Price:", highest_price)
lowest_price = sales["Price"].min()
print("Lowest Price:", lowest_price)
total_quantity = sales["Quantity"].sum()
print("Total Quantity:", total_quantity)
print(sales.describe())
The describe() command provides useful statistical
information such as count, mean, minimum, maximum, and quartiles
for numerical columns.
Let's put some of the skills together. We will create a student results dataset, remove duplicate records, handle missing scores, and calculate the average score.
import pandas as pd
students = {
"Name": ["Ada", "Tunde", "Chika", "Ada", "Bola"],
"Score": [85, 70, None, 85, 60],
"Class": ["JSS2", "JSS2", "JSS2", "JSS2", "JSS2"]
}
results = pd.DataFrame(students)
print("Original Data:")
print(results)
# Remove duplicate records
results = results.drop_duplicates()
# Fill missing scores with the average score
results["Score"] = results["Score"].fillna(
results["Score"].mean()
)
# Calculate average score
average = results["Score"].mean()
print("Cleaned Data:")
print(results)
print("Average Score:", average)
What did we do?
In this module, you have learned that:
isnull().dropna() removes rows with missing values.fillna() replaces missing values.drop_duplicates() removes repeated rows.sort_values() arranges data in order.mean(), max(), and min() help us analyse numbers.describe() provides a statistical summary.Answer the following questions using Python and Pandas:
Imagine you are helping a school in Ibadan organise its examination results. The dataset contains students' names, subjects, and scores. Some records are repeated, and some scores are missing.
Your task is to:
Challenge goal: Demonstrate how Python and Pandas can turn an untidy dataset into useful information that a school can use to understand students' performance.
You have completed Module 7. You now understand how to clean data, correct common problems, and perform basic analysis using Python and Pandas.
In the next module, you will learn how to create charts and visualise data so that people can understand information more easily.