# 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 1. What is the difference between a Series and a DataFrame in Pandas? 2. How do you import Pandas and what is the conventional alias? 3. Explain the difference between `.loc[]` and `.iloc[]`. 4. What does `df.head(10)` return? ### Module 3–4: Jupyter and Pandas Basics 5. What is a list comprehension and how does it differ from a for loop? 6. How do you create a DataFrame from a dictionary of lists? 7. Explain the difference between `axis=0` and `axis=1`. 8. What does `df.describe()` tell you about your data? ### Module 5–6: Reading Data and Inspection 9. What parameters does `pd.read_csv()` accept for handling missing values? 10. How do you check the memory usage of a DataFrame? 11. What is the difference between `.info()` and `.dtypes`? ### Module 7–8: Data Cleaning and Manipulation 12. When would you use `.fillna()` vs `.dropna()`? 13. How do you detect and remove duplicate rows? 14. What is the difference between `.apply()` and `.map()`? ### Module 9–10: Aggregation and Merging 15. Explain the split-apply-combine pattern used by `.groupby()`. 16. What is the difference between inner, left, right, and outer joins? 17. How do you create a pivot table in Pandas? ### Module 11–12: Time Series and Visualization 18. What is the difference between `.resample()` and `.rolling()`? 19. How do you parse dates when reading a CSV file? 20. How do you create subplots with Pandas plotting? --- ## Coding Exercises ### Exercise 1: DataFrame Basics ```python 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 ``` 1. Select all rows where salary > 55000 2. Add a column `Bonus` calculated as 10% of salary 3. Filter employees in IT department with age > 28 ### Exercise 2: GroupBy Operations ```python 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), }) ``` 1. Group by Category and compute mean, std, and count of Value 2. Group by both Category and Group, then unstack the result 3. Add a column showing each row's percentage of its category total ### Exercise 3: Data Cleaning ```python 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], }) ``` 1. Strip whitespace and convert names to title case 2. Replace "unknown" and "N/A" with NaN 3. Convert Age and Salary to numeric, coerce errors to NaN 4. Impute missing numeric values with the median 5. Remove duplicate rows ### Exercise 4: Merge and Join ```python 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], }) ``` 1. Perform a left join of customers and orders 2. Perform a full outer join — what do you notice? 3. Merge on `CustomerID` but rename it in one DataFrame first ### Exercise 5: Time Series ```python dates = pd.date_range("2024-01-01", periods=30, freq="D") ts = pd.Series(np.random.randint(100, 300, 30), index=dates, name="Sales") ``` 1. Compute a 7-day rolling average 2. Resample to weekly frequency with sum aggregation 3. Calculate the day-over-day percentage change ### Exercise 6: Visualization Using the DataFrame from Exercise 1: 1. Create a bar chart of average Salary by Department 2. Create a histogram of Age with 10 bins 3. Create a scatter plot of Age vs Salary --- ## Challenge Problems ### Challenge 1: Sales Analysis Pipeline ```python # 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:** 1. Add a `Revenue` column (`Quantity * Price`) 2. Which store has the highest total revenue? 3. Which product is the best-selling by quantity? 4. Create a pivot table showing average revenue by Store (rows) and Product (columns) 5. Find the top 3 hours of the day by total sales 6. Compute the percentage of revenue from each customer type per store 7. Create a bar chart comparing store performance ### Challenge 2: Multi-Dataset Merger ```python # 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:** 1. Merge all three datasets into a single DataFrame 2. Calculate average session duration per plan type 3. Find users who have made payments but have no sessions 4. Create a summary table: total revenue, total sessions, and avg duration per plan 5. Identify the top 10 users by total payment amount 6. Compute the correlation between pages viewed and session duration ### Challenge 3: Weather Anomaly Detection ```python 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:** 1. Compute the 30-year daily climatology (average for each calendar day) 2. Identify days where temperature exceeds 2 standard deviations from the climatology 3. Detect heatwaves (≥3 consecutive days above the 90th percentile) 4. Create a column for temperature anomaly (actual - climatology) 5. Visualise the temperature trend with a 90-day rolling average 6. Count the number of extreme events per year --- ## Quizzes ### Quiz 1: Fundamentals 1. 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])` 2. Which method returns the first 5 rows of a DataFrame? - a) `.first(5)` - b) `.head(5)` - c) `.top(5)` - d) `.begin(5)` 3. How do you select column "Age" from DataFrame `df`? - a) `df["Age"]` - b) `df.Age` - c) Both a and b are correct - d) `df[0]` 4. The `iloc[]` indexer uses: - a) Label-based indexing - b) Integer position-based indexing - c) Boolean indexing - d) String-based indexing ### Quiz 2: Data Manipulation 5. 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 6. Which parameter controls the join type in `pd.merge()`? - a) `type` - b) `join` - c) `how` - d) `method` 7. 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 8. Which resample frequency alias represents "month end"? - a) `ME` - b) `M` - c) `MS` - d) `MONTH` ### Quiz 3: Advanced Topics 9. 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 10. 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:** 1. Load and clean the data (handle missing values, correct dtypes) 2. Create a summary table of churn rates by contract type 3. Generate histograms of tenure and monthly charges, segmented by churn status 4. Compute average charges for churned vs non-churned customers 5. Create a bar chart showing churn rate by contract type 6. Export the cleaned dataset and a summary report ### Assignment 2: Financial Portfolio Analysis **Duration:** 2–3 hours **Tasks:** 1. Load historical prices for 3–5 stocks from CSV files 2. Calculate daily returns for each stock 3. Compute rolling 20-day volatility for each stock 4. Create a correlation matrix of stock returns 5. Calculate portfolio returns assuming equal weighting 6. 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 ```python # 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 ## Further Reading - [Pandas Cheat Sheet](https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf) - [LeetCode Pandas Questions](https://leetcode.com/problemset/pandas/) - [HackerRank Python (Pandas)](https://www.hackerrank.com/domains/python)