Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to Python for Data Analysis ยท 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: Data Cleaning and Basic Data Analysis** โ€” a beginner-friendly lesson designed for 13-year-olds, with practical Python and Pandas examples. Module 7: Data Cleaning and Basic Data Analysis

Module 7: Data Cleaning and Basic Data Analysis

Introduction

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.

Learning Objectives

By the end of this module, you should be able to:

  • Explain data cleaning and why it is important.
  • Identify missing and duplicate data.
  • Remove duplicate records using Pandas.
  • Handle missing values.
  • Correct simple data errors.
  • Change incorrect data types.
  • Sort and filter datasets.
  • Perform basic data analysis using Pandas.

1. What Is Data Cleaning?

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.

2. Why Is Data Cleaning Important?

Data cleaning helps us to:

  • Reduce mistakes in reports.
  • Improve the quality of information.
  • Remove repeated records.
  • Handle missing information.
  • Make data easier to understand.
  • Make analysis and business decisions more reliable.

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.

3. Common Data Quality Problems

A. Missing Values

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.

B. Duplicate Records

Duplicate records are repeated entries in a dataset. For example, the same student may appear twice in a school results table.

C. Incorrect Information

This happens when information is entered wrongly. For example, a product price may be entered as โ‚ฆ50000 instead of โ‚ฆ5,000.

D. Inconsistent Text

The same information may be written in different ways. For example, a city may appear as "Lagos", "lagos", and "LAGOS".

E. Incorrect Data Types

A number may accidentally be stored as text. This can make mathematical calculations difficult.

4. Creating a Dataset with Errors

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.

5. Identifying Missing Values

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.

6. Handling Missing Values

There are different ways to handle missing values. The best method depends on what the missing information represents.

Method 1: Removing Rows with Missing Values

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.

Method 2: Filling Missing Values

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.

7. Removing Duplicate Records

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.

8. Correcting Inconsistent Text

Sometimes the same information is written using different capital letters or extra spaces.

For example:

  • Lagos
  • lagos
  • LAGOS

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.

9. Changing Data Types

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.

10. Sorting Data

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)

11. Filtering Data

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)

12. Performing Basic Data Analysis

After cleaning our data, we can begin analysing it to discover useful information.

A. Calculate the Average Price

average_price = sales["Price"].mean()

print("Average Price:", average_price)

B. Find the Highest Price

highest_price = sales["Price"].max()

print("Highest Price:", highest_price)

C. Find the Lowest Price

lowest_price = sales["Price"].min()

print("Lowest Price:", lowest_price)

D. Calculate Total Quantity Sold

total_quantity = sales["Quantity"].sum()

print("Total Quantity:", total_quantity)

E. Get a Statistical Summary

print(sales.describe())

The describe() command provides useful statistical information such as count, mean, minimum, maximum, and quartiles for numerical columns.

13. A Complete Data Cleaning Example

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?

  1. Created a table containing student results.
  2. Identified and removed a repeated student record.
  3. Replaced the missing score with the average of available scores.
  4. Calculated the average score of the cleaned dataset.

14. Important Data Cleaning Rules

  • Always keep a copy of the original dataset.
  • Check missing values before performing calculations.
  • Do not remove records without understanding them.
  • Check duplicate records carefully.
  • Make sure numbers and dates use the correct data types.
  • Use sensible replacement values for missing information.
  • Review the cleaned dataset before using it in a report.

15. Module Summary

In this module, you have learned that:

  • Data cleaning improves the quality of a dataset.
  • Missing values can be identified using isnull().
  • dropna() removes rows with missing values.
  • fillna() replaces missing values.
  • drop_duplicates() removes repeated rows.
  • sort_values() arranges data in order.
  • Filtering helps us find specific records.
  • mean(), max(), and min() help us analyse numbers.
  • describe() provides a statistical summary.

16. Practical Exercises

Answer the following questions using Python and Pandas:

  1. Create a DataFrame containing five products and their prices.
  2. Add one missing price to your dataset.
  3. Use Pandas to identify the missing value.
  4. Fill the missing price with the average price.
  5. Add a duplicate product record and remove the duplicate.
  6. Sort the products from highest price to lowest price.
  7. Filter products with prices above โ‚ฆ3,000.
  8. Calculate the average, highest, and lowest prices.

17. Practical Challenge: Clean a School Results Dataset

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:

  1. Create a DataFrame containing at least six student records.
  2. Include at least one missing score.
  3. Include one duplicate record.
  4. Identify all missing values.
  5. Remove duplicate records.
  6. Fill missing scores using a suitable method.
  7. Find the highest and lowest scores.
  8. Calculate the average score.
  9. Display students who scored 50 or above.
  10. Save the cleaned results as a CSV file.

Challenge goal: Demonstrate how Python and Pandas can turn an untidy dataset into useful information that a school can use to understand students' performance.

Congratulations!

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.

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