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.
By the end of this module, you should be able to:
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.
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.
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.
Sometimes a dataset contains thousands of rows. Instead of displaying everything, we can use Pandas commands to view only a small part.
print(shop.head())
print(shop.tail())
print(shop.shape)
The shape command returns two numbers: the number of rows
and the number of columns.
shop.info()
This command shows useful information such as column names, the number of entries, and the data types.
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"]])
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.
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.
Pandas can help us calculate totals, averages, highest values, and lowest values.
print(shop["Price"].mean())
print(shop["Price"].max())
print(shop["Price"].min())
print(shop["Quantity"].sum())
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.
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.
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.
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:
Pandas is useful because it helps data analysts to:
In this module, you have learned that:
head() displays the first few rows.tail() displays the last few rows.iloc[] selects rows by position.Try answering these questions using Python and Pandas:
You are helping a shop owner organise daily sales. Create a Pandas DataFrame containing at least five products.
Your table should contain:
Complete these tasks:
Challenge goal: Use Pandas to turn a simple list of shop sales into useful information that can help the shop owner make better decisions.
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.