Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to Python for Data Analysis ยท Lesson 7 of 9

Module Six

๐Ÿ“– 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.
7
Module 6: Working with Data Using Pandas** โ€” beginner-friendly lesson for 13-year-olds, with practical Python examples and exercises. Module 6: Working with Data Using Pandas

Module 6: Working with Data Using Pandas

Introduction

Imagine you own a small shop in Lagos. Every day, you sell rice, bread, milk, and other products. You want to know which product sells the most and how much money your shop makes.

You could write everything in a notebook, but checking hundreds or thousands of sales records would take a lot of time. This is where Pandas becomes useful.

Pandas is a Python library that helps us organise, read, manage, and analyse data. It works especially well with information stored in tables.

Learning Objectives

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

  • Explain what Pandas is used for.
  • Import the Pandas library into Python.
  • Create a Pandas DataFrame.
  • Read and display data.
  • Select rows and columns.
  • Filter data using conditions.
  • Calculate simple totals and averages.
  • Save data into a CSV file.

1. What Is Pandas?

Pandas is a Python library used for working with data. It makes it easier to organise information into rows and columns, similar to a spreadsheet in Microsoft Excel.

For example, a school may keep students' names, ages, classes, and scores in a table. Pandas can help us work with this information.

2. Installing and Importing Pandas

Before using Pandas on your computer, you may need to install it. Open your terminal or command prompt and type:

pip install pandas

After installation, import Pandas into your Python program:

import pandas as pd

The letters pd are a short name we use when writing Pandas commands. This saves us from typing the full word every time.

3. Understanding a DataFrame

A DataFrame is one of the most important parts of Pandas. It is a table containing data arranged in rows and columns.

Let's create a table showing the sales of a small shop:

import pandas as pd

data = {
    "Product": ["Rice", "Bread", "Milk", "Sugar"],
    "Price": [5000, 1500, 2500, 3000],
    "Quantity": [4, 10, 6, 5]
}

shop = pd.DataFrame(data)

print(shop)

Expected output:

  Product  Price  Quantity
0    Rice   5000         4
1   Bread   1500        10
2    Milk   2500         6
3   Sugar   3000         5

Notice that each product has its own row, while Product, Price, and Quantity are the column names.

4. Viewing Data

Sometimes a dataset contains thousands of rows. Instead of displaying everything, we can use Pandas commands to view only a small part.

Display the first five rows

print(shop.head())

Display the last five rows

print(shop.tail())

Check the number of rows and columns

print(shop.shape)

The shape command returns two numbers: the number of rows and the number of columns.

Get information about the dataset

shop.info()

This command shows useful information such as column names, the number of entries, and the data types.

5. Selecting Columns

You may not need every column in a dataset. Pandas allows you to select only the information you want.

To display only the Product column:

print(shop["Product"])

To display only the Price column:

print(shop["Price"])

To display Product and Quantity together:

print(shop[["Product", "Quantity"]])

6. Selecting Rows

Rows contain individual records. Pandas allows us to select a particular row using its position or label.

To display the first row:

print(shop.iloc[0])

To display the second row:

print(shop.iloc[1])

Remember that Python starts counting from zero. This means the first row has position 0, the second has position 1, and so on.

7. Filtering Data

Filtering means showing only records that meet a particular condition. For example, you may want to see products that cost more than โ‚ฆ2,000.

expensive_products = shop[shop["Price"] > 2000]

print(expensive_products)

Expected output:

  Product  Price  Quantity
0    Rice   5000         4
2    Milk   2500         6
3   Sugar   3000         5

The condition shop["Price"] > 2000 tells Pandas to show only products whose prices are greater than 2,000.

8. Performing Calculations with Pandas

Pandas can help us calculate totals, averages, highest values, and lowest values.

Calculate the average price

print(shop["Price"].mean())

Find the highest price

print(shop["Price"].max())

Find the lowest price

print(shop["Price"].min())

Calculate the total quantity

print(shop["Quantity"].sum())

9. Creating a New Column

We can use Pandas to create a new column from existing information. For example, we can calculate the total value of each product by multiplying its price by its quantity.

shop["Total Value"] = shop["Price"] * shop["Quantity"]

print(shop)

Expected output:

  Product  Price  Quantity  Total Value
0    Rice   5000         4        20000
1   Bread   1500        10        15000
2    Milk   2500         6        15000
3   Sugar   3000         5        15000

The new column shows the total value of each product based on its price and quantity.

10. Reading Data from a CSV File

A CSV file is a simple file format used to store information in rows and columns. You can create one using Microsoft Excel or another spreadsheet application.

To read a CSV file with Pandas, use:

import pandas as pd

data = pd.read_csv("sales.csv")

print(data)

Make sure the CSV file is in the correct folder or provide its full file path.

11. Saving Data into a CSV File

After working on a dataset, you may want to save your changes so that you can use them later.

shop.to_csv("shop_report.csv", index=False)

This command saves the DataFrame as a CSV file called shop_report.csv. The index=False setting prevents Pandas from adding an extra index column to the file.

12. Practical Example: Analysing Students' Scores

Imagine a teacher wants to analyse the examination scores of four students. We can use Pandas to organise and study their results.

import pandas as pd

students = {
    "Name": ["Ada", "Tunde", "Chika", "Bola"],
    "Score": [85, 65, 92, 48]
}

results = pd.DataFrame(students)

print(results)

print("Average Score:", results["Score"].mean())

passed = results[results["Score"] >= 50]

print("Students who passed:")
print(passed)

What this program does:

  • Creates a table containing students' names and scores.
  • Calculates the average examination score.
  • Displays students who scored 50 or above.

13. Why Is Pandas Important in Data Analysis?

Pandas is useful because it helps data analysts to:

  • Organise large amounts of information.
  • Read data from CSV and Excel files.
  • Select important rows and columns.
  • Filter information based on conditions.
  • Calculate totals and averages.
  • Prepare data for charts and reports.
  • Clean and transform datasets.

14. Module Summary

In this module, you have learned that:

  • Pandas is a Python library for working with data.
  • A DataFrame is a table containing rows and columns.
  • head() displays the first few rows.
  • tail() displays the last few rows.
  • iloc[] selects rows by position.
  • Columns can be selected using their names.
  • Filtering helps us find records that meet conditions.
  • Pandas can calculate totals, averages, maximums, and minimums.
  • Pandas can read and save CSV files.

15. Practical Exercises

Try answering these questions using Python and Pandas:

  1. Create a DataFrame containing five students and their examination scores.
  2. Display only the students' names.
  3. Display the first three records.
  4. Find the average examination score.
  5. Filter the students who scored 70 or above.
  6. Find the highest and lowest scores.
  7. Save the student records into a CSV file.

16. Practical Challenge: Build a Shop Sales Report

You are helping a shop owner organise daily sales. Create a Pandas DataFrame containing at least five products.

Your table should contain:

  • Product name
  • Product price
  • Quantity sold

Complete these tasks:

  1. Display all products in a table.
  2. Calculate the total value of each product.
  3. Find the product with the highest price.
  4. Display products with a price above โ‚ฆ2,000.
  5. Calculate the total quantity sold.
  6. Save your completed report as a CSV file.

Challenge goal: Use Pandas to turn a simple list of shop sales into useful information that can help the shop owner make better decisions.

Congratulations!

You have completed Module 6. You now know how to use Pandas to organise, view, filter, calculate, and save data. In the next module, you will learn how to clean data and perform basic data analysis.

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