Module 15: Exercises and Practice
Learning Objectives
By the end of this module, you will be able to:
Apply Pandas concepts to solve structured practice problems
Complete coding exercises that test specific skills
Tackle challenge problems requiring multi-step solutions
Assess your knowledge through quizzes and assignments
Note
Consistent practice is the key to mastering Pandas. This module provides a variety of exercise types — from quick drills to comprehensive challenges — designed to reinforce every concept covered in the course.
Exercise Types
This module offers five types of exercises:
Type |
Description |
Time Estimate |
Best For |
|---|---|---|---|
Practice Questions |
Short-answer conceptual questions |
5–10 min |
Quick review |
Coding Exercises |
Focused code-based problems |
15–30 min |
Skill reinforcement |
Challenge Problems |
Multi-step data analysis tasks |
30–60 min |
Deep learning |
Quizzes |
Multiple-choice and fill-in-the-blank |
10–20 min |
Knowledge check |
Assignments |
Comprehensive mini-projects |
1–3 hours |
Assessment |
Practice Questions
Module 1–2: Introduction and Python Refresher
What is the difference between a Series and a DataFrame in Pandas?
How do you import Pandas and what is the conventional alias?
Explain the difference between
.loc[]and.iloc[].What does
df.head(10)return?
Module 3–4: Jupyter and Pandas Basics
What is a list comprehension and how does it differ from a for loop?
How do you create a DataFrame from a dictionary of lists?
Explain the difference between
axis=0andaxis=1.What does
df.describe()tell you about your data?
Module 5–6: Reading Data and Inspection
What parameters does
pd.read_csv()accept for handling missing values?How do you check the memory usage of a DataFrame?
What is the difference between
.info()and.dtypes?
Module 7–8: Data Cleaning and Manipulation
When would you use
.fillna()vs.dropna()?How do you detect and remove duplicate rows?
What is the difference between
.apply()and.map()?
Module 9–10: Aggregation and Merging
Explain the split-apply-combine pattern used by
.groupby().What is the difference between inner, left, right, and outer joins?
How do you create a pivot table in Pandas?
Module 11–12: Time Series and Visualization
What is the difference between
.resample()and.rolling()?How do you parse dates when reading a CSV file?
How do you create subplots with Pandas plotting?
Coding Exercises
Exercise 1: DataFrame Basics
import pandas as pd
import numpy as np
# Create this DataFrame:
# Name Age Salary Department
# Alice 25 50000 HR
# Bob 30 60000 IT
# Charlie 35 70000 IT
# Diana 28 55000 HR
Select all rows where salary > 55000
Add a column
Bonuscalculated as 10% of salaryFilter employees in IT department with age > 28
Exercise 2: GroupBy Operations
np.random.seed(42)
df = pd.DataFrame({
"Category": np.random.choice(["A", "B", "C"], 100),
"Value": np.random.randn(100),
"Group": np.random.choice(["X", "Y"], 100),
})
Group by Category and compute mean, std, and count of Value
Group by both Category and Group, then unstack the result
Add a column showing each row’s percentage of its category total
Exercise 3: Data Cleaning
dirty = pd.DataFrame({
"Name": [" Alice ", "Bob", "CHARLIE", None, "diana", "Bob"],
"Age": [30, "unknown", -5, 25, 40, 30],
"Salary": [50000, 60000, None, "55,000", "N/A", 60000],
})
Strip whitespace and convert names to title case
Replace “unknown” and “N/A” with NaN
Convert Age and Salary to numeric, coerce errors to NaN
Impute missing numeric values with the median
Remove duplicate rows
Exercise 4: Merge and Join
customers = pd.DataFrame({
"CustomerID": [1, 2, 3, 4],
"Name": ["Alice", "Bob", "Charlie", "Diana"],
})
orders = pd.DataFrame({
"OrderID": [101, 102, 103, 104],
"CustomerID": [1, 2, 2, 5],
"Amount": [250, 450, 300, 700],
})
Perform a left join of customers and orders
Perform a full outer join — what do you notice?
Merge on
CustomerIDbut rename it in one DataFrame first
Exercise 5: Time Series
dates = pd.date_range("2024-01-01", periods=30, freq="D")
ts = pd.Series(np.random.randint(100, 300, 30), index=dates, name="Sales")
Compute a 7-day rolling average
Resample to weekly frequency with sum aggregation
Calculate the day-over-day percentage change
Exercise 6: Visualization
Using the DataFrame from Exercise 1:
Create a bar chart of average Salary by Department
Create a histogram of Age with 10 bins
Create a scatter plot of Age vs Salary
Challenge Problems
Challenge 1: Sales Analysis Pipeline
# Generate sales dataset
np.random.seed(42)
n = 1000
sales = pd.DataFrame({
"Date": pd.date_range("2024-01-01", periods=n, freq="h")[:n],
"Store": np.random.choice(["Store_A", "Store_B", "Store_C"], n),
"Product": np.random.choice(["Widget", "Gadget", "Doohickey"], n),
"Quantity": np.random.randint(1, 20, n),
"Price": np.round(np.random.uniform(10, 100, n), 2),
"Customer_Type": np.random.choice(["New", "Returning", "VIP"], n, p=[0.3, 0.5, 0.2]),
})
Tasks:
Add a
Revenuecolumn (Quantity * Price)Which store has the highest total revenue?
Which product is the best-selling by quantity?
Create a pivot table showing average revenue by Store (rows) and Product (columns)
Find the top 3 hours of the day by total sales
Compute the percentage of revenue from each customer type per store
Create a bar chart comparing store performance
Challenge 2: Multi-Dataset Merger
# Three related datasets
users = pd.DataFrame({
"user_id": range(1, 101),
"name": [f"User_{i}" for i in range(1, 101)],
"signup_date": pd.date_range("2024-01-01", periods=100, freq="D"),
"plan": np.random.choice(["Free", "Pro", "Enterprise"], 100, p=[0.5, 0.3, 0.2]),
})
sessions = pd.DataFrame({
"session_id": range(1, 501),
"user_id": np.random.randint(1, 101, 500),
"start_time": pd.date_range("2024-04-01", periods=500, freq="h"),
"duration_min": np.random.randint(5, 120, 500),
"pages_viewed": np.random.randint(1, 20, 500),
})
payments = pd.DataFrame({
"payment_id": range(1, 201),
"user_id": np.random.randint(1, 101, 200),
"amount": np.round(np.random.uniform(10, 200, 200), 2),
"payment_date": pd.date_range("2024-04-01", periods=200, freq="D"),
})
Tasks:
Merge all three datasets into a single DataFrame
Calculate average session duration per plan type
Find users who have made payments but have no sessions
Create a summary table: total revenue, total sessions, and avg duration per plan
Identify the top 10 users by total payment amount
Compute the correlation between pages viewed and session duration
Challenge 3: Weather Anomaly Detection
np.random.seed(42)
dates = pd.date_range("2020-01-01", "2024-12-31", freq="D")
n = len(dates)
weather = pd.DataFrame({
"Temperature": 20 + 10 * np.sin(2 * np.pi * np.arange(n) / 365 - 1.5) + np.random.normal(0, 4, n),
"Humidity": np.random.uniform(30, 90, n),
"Wind_Speed": np.random.exponential(5, n),
}, index=dates)
Tasks:
Compute the 30-year daily climatology (average for each calendar day)
Identify days where temperature exceeds 2 standard deviations from the climatology
Detect heatwaves (≥3 consecutive days above the 90th percentile)
Create a column for temperature anomaly (actual - climatology)
Visualise the temperature trend with a 90-day rolling average
Count the number of extreme events per year
Quizzes
Quiz 1: Fundamentals
What is the correct way to create a Series from a list
[1, 2, 3]?a)
pd.series([1, 2, 3])b)
pd.Series([1, 2, 3])c)
pd.DataFrame([1, 2, 3])d)
Series([1, 2, 3])
Which method returns the first 5 rows of a DataFrame?
a)
.first(5)b)
.head(5)c)
.top(5)d)
.begin(5)
How do you select column “Age” from DataFrame
df?a)
df["Age"]b)
df.Agec) Both a and b are correct
d)
df[0]
The
iloc[]indexer uses:a) Label-based indexing
b) Integer position-based indexing
c) Boolean indexing
d) String-based indexing
Quiz 2: Data Manipulation
What does
df.dropna()do by default?a) Drops columns with any NaN
b) Drops rows with any NaN
c) Fills NaN with zero
d) Removes duplicate rows
Which parameter controls the join type in
pd.merge()?a)
typeb)
joinc)
howd)
method
The
.groupby().transform()method:a) Returns aggregated results
b) Returns results in the original shape
c) Filters groups based on a condition
d) Creates a pivot table
Which resample frequency alias represents “month end”?
a)
MEb)
Mc)
MSd)
MONTH
Quiz 3: Advanced Topics
Categorical dtype is most memory-efficient when:
a) All values are unique
b) Number of unique values is small relative to total
c) The column contains numeric data
d) The column has high cardinality
Which is the fastest way to add two columns element-wise?
a)
df.apply(lambda r: r['A'] + r['B'], axis=1)b)
df['A'] + df['B']c) A for loop over rows
d)
df.itertuples()
Assignments
Assignment 1: Customer Churn Analysis
Duration: 1–2 hours
Dataset: Create or load a customer dataset with columns: CustomerID, Tenure, MonthlyCharges, TotalCharges, Contract, Churn
Tasks:
Load and clean the data (handle missing values, correct dtypes)
Create a summary table of churn rates by contract type
Generate histograms of tenure and monthly charges, segmented by churn status
Compute average charges for churned vs non-churned customers
Create a bar chart showing churn rate by contract type
Export the cleaned dataset and a summary report
Assignment 2: Financial Portfolio Analysis
Duration: 2–3 hours
Tasks:
Load historical prices for 3–5 stocks from CSV files
Calculate daily returns for each stock
Compute rolling 20-day volatility for each stock
Create a correlation matrix of stock returns
Calculate portfolio returns assuming equal weighting
Generate a report with visualisations of performance and risk metrics
Solutions
Solutions for all exercises, challenges, quizzes, and assignments are available in the solutions/ directory at the root of this course repository.
Warning
Attempt to solve each problem on your own before consulting the solutions. The learning comes from the struggle, not from reading the answer.
Accessing Solutions
# Solutions are organised by module
# Example solution file location:
# solutions/module15/exercise_1_solution.py
# You can load and run solution code:
# %run solutions/module15/exercise_1_solution.py
Summary
Practice questions test conceptual understanding of each module
Coding exercises provide focused, skill-specific practice
Challenge problems combine multiple skills into realistic tasks
Quizzes assess your knowledge with multiple-choice questions
Assignments are comprehensive assessments for deeper learning
All solutions are available — but use them wisely