{ "cells": [ { "cell_type": "markdown", "id": "669debb3", "metadata": {}, "source": [ "# 🚀 Pandas Practice Exercise 2: Real-World Scenarios & Advanced Analysis\n", "\n", "This notebook contains **15 scenario-based challenges** reflecting real-world data engineering and analytics tasks in Pandas:\n", "- Conditional feature engineering (`np.where`)\n", "- De-duplication and integrity checks\n", "- Regular expression string extraction\n", "- Datetime calculations & elapsed periods\n", "- Stacking and joining relational tables (`pd.concat`, `pd.merge`)\n", "- Anti-joins to detect unmatched records\n", "- Two-dimensional summaries via Pivot Tables\n", "- Tidying wide datasets with `pd.melt()`\n", "- Performance rankings and running cumulative metrics\n", "- Categorical memory optimization\n", "- Discretization & binning (`pd.cut`)\n", "- End-to-end fluent data cleaning pipelines\n", "\n", "### 📝 Instructions:\n", "1. Write your solutions in the designated code cells.\n", "2. Run each cell to confirm that your logic produces expected outcomes.\n", "3. Detailed solutions and derivations are available in `05_pandas_exercise_2_solutions.ipynb`." ] }, { "cell_type": "code", "execution_count": null, "id": "b4197b43", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np" ] }, { "cell_type": "markdown", "id": "8580dee3", "metadata": {}, "source": [ "### Problem 1: Vectorized Conditional Columns with np.where\n", "\n", "Given a DataFrame of employee performance scores:\n", "```python\n", "df = pd.DataFrame({\n", " 'Employee': ['Amy', 'Brad', 'Chris', 'Dana', 'Eric'],\n", " 'Score': [92, 68, 74, 85, 59]\n", "})\n", "```\n", "Use `np.where` to create a new column `'Performance'`:\n", "- `'Excellent'` if Score >= 85\n", "- `'Satisfactory'` if Score >= 70 but < 85\n", "- `'Needs Improvement'` if Score < 70" ] }, { "cell_type": "code", "execution_count": null, "id": "4ddc0f9a", "metadata": {}, "outputs": [], "source": [ "df = pd.DataFrame({\n", " 'Employee': ['Amy', 'Brad', 'Chris', 'Dana', 'Eric'],\n", " 'Score': [92, 68, 74, 85, 59]\n", "})\n", "\n", "# Add 'Performance' column using np.where\n" ] }, { "cell_type": "markdown", "id": "be56e29a", "metadata": {}, "source": [ "### Problem 2: Identifying & Removing Duplicate Records\n", "\n", "Given a customer transaction log with accidental double-entries:\n", "```python\n", "logs = pd.DataFrame({\n", " 'Tx_ID': [101, 102, 102, 103, 104, 104],\n", " 'Customer': ['Alice', 'Bob', 'Bob', 'Charlie', 'Alice', 'Alice'],\n", " 'Amount': [50.0, 75.0, 75.0, 120.0, 200.0, 200.0]\n", "})\n", "```\n", "1. Identify duplicate rows using `.duplicated()`.\n", "2. Drop exact duplicates while keeping the first occurrence." ] }, { "cell_type": "code", "execution_count": null, "id": "d124448e", "metadata": {}, "outputs": [], "source": [ "logs = pd.DataFrame({\n", " 'Tx_ID': [101, 102, 102, 103, 104, 104],\n", " 'Customer': ['Alice', 'Bob', 'Bob', 'Charlie', 'Alice', 'Alice'],\n", " 'Amount': [50.0, 75.0, 75.0, 120.0, 200.0, 200.0]\n", "})\n", "\n", "# Find and drop duplicates\n" ] }, { "cell_type": "markdown", "id": "71ec0370", "metadata": {}, "source": [ "### Problem 3: Regex Pattern Extraction with .str.extract()\n", "\n", "Given a DataFrame with messy contact strings:\n", "```python\n", "contacts = pd.DataFrame({\n", " 'Raw_Contact': [\n", " 'John Doe (555-1234)',\n", " 'Jane Smith (555-5678)',\n", " 'Bob Johnson (555-9012)'\n", " ]\n", "})\n", "```\n", "Use `.str.extract()` with regex capture groups `r'^(.*?) \\((.*?)\\)'` to extract `'Name'` and `'Phone'` into separate columns." ] }, { "cell_type": "code", "execution_count": null, "id": "c378817d", "metadata": {}, "outputs": [], "source": [ "contacts = pd.DataFrame({\n", " 'Raw_Contact': [\n", " 'John Doe (555-1234)',\n", " 'Jane Smith (555-5678)',\n", " 'Bob Johnson (555-9012)'\n", " ]\n", "})\n", "\n", "# Extract Name and Phone\n" ] }, { "cell_type": "markdown", "id": "eaa8b053", "metadata": {}, "source": [ "### Problem 4: Calculating Duration and Elapsed Days\n", "\n", "Given subscription start and end dates:\n", "```python\n", "subs = pd.DataFrame({\n", " 'User': ['UserA', 'UserB', 'UserC'],\n", " 'Start': ['2025-01-10', '2025-03-01', '2025-06-15'],\n", " 'End': ['2025-04-10', '2025-03-31', '2026-06-15']\n", "})\n", "```\n", "1. Convert `'Start'` and `'End'` to datetime.\n", "2. Compute `'Duration_Days'` as integer days elapsed.\n", "3. Identify subscriptions lasting longer than 100 days." ] }, { "cell_type": "code", "execution_count": null, "id": "656df837", "metadata": {}, "outputs": [], "source": [ "subs = pd.DataFrame({\n", " 'User': ['UserA', 'UserB', 'UserC'],\n", " 'Start': ['2025-01-10', '2025-03-01', '2025-06-15'],\n", " 'End': ['2025-04-10', '2025-03-31', '2026-06-15']\n", "})\n", "\n", "# Calculate duration in days\n" ] }, { "cell_type": "markdown", "id": "74ae0fa0", "metadata": {}, "source": [ "### Problem 5: Stacking Multiple Datasets with pd.concat()\n", "\n", "Given two sales tables for different quarters:\n", "```python\n", "q1 = pd.DataFrame({'Region': ['North', 'South'], 'Revenue': [45000, 32000]})\n", "q2 = pd.DataFrame({'Region': ['North', 'South'], 'Revenue': [51000, 39000]})\n", "```\n", "Concatenate them into a single table with an added `'Quarter'` identifier, and reset the index." ] }, { "cell_type": "code", "execution_count": null, "id": "d6f242a4", "metadata": {}, "outputs": [], "source": [ "q1 = pd.DataFrame({'Region': ['North', 'South'], 'Revenue': [45000, 32000]})\n", "q2 = pd.DataFrame({'Region': ['North', 'South'], 'Revenue': [51000, 39000]})\n", "\n", "# Concatenate tables\n" ] }, { "cell_type": "markdown", "id": "af2913fd", "metadata": {}, "source": [ "### Problem 6: Relational Joins with pd.merge()\n", "\n", "Given:\n", "```python\n", "employees = pd.DataFrame({\n", " 'Emp_ID': [1, 2, 3, 4],\n", " 'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],\n", " 'Dept_ID': [10, 20, 10, 30]\n", "})\n", "\n", "departments = pd.DataFrame({\n", " 'Dept_ID': [10, 20, 40],\n", " 'Dept_Name': ['Engineering', 'Marketing', 'Legal']\n", "})\n", "```\n", "1. Perform an `inner` join on `'Dept_ID'`.\n", "2. Perform a `left` join keeping all employees." ] }, { "cell_type": "code", "execution_count": null, "id": "d3c66390", "metadata": {}, "outputs": [], "source": [ "employees = pd.DataFrame({\n", " 'Emp_ID': [1, 2, 3, 4],\n", " 'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],\n", " 'Dept_ID': [10, 20, 10, 30]\n", "})\n", "\n", "departments = pd.DataFrame({\n", " 'Dept_ID': [10, 20, 40],\n", " 'Dept_Name': ['Engineering', 'Marketing', 'Legal']\n", "})\n", "\n", "# Inner and Left joins\n" ] }, { "cell_type": "markdown", "id": "3aa733a6", "metadata": {}, "source": [ "### Problem 7: Finding Unmatched Records (Anti-Join Pattern)\n", "\n", "Using `employees` and `departments` from Problem 6, identify employees who belong to a department that does NOT exist in the `departments` table (e.g. Diana in Dept 30).\n", "*Hint:* Use `how='left'` with `indicator=True`." ] }, { "cell_type": "code", "execution_count": null, "id": "1a47b618", "metadata": {}, "outputs": [], "source": [ "# Anti-join using indicator=True\n" ] }, { "cell_type": "markdown", "id": "6d07adb6", "metadata": {}, "source": [ "### Problem 8: Pivot Tables for 2D Summaries\n", "\n", "Given sales transactions across multiple regions and product categories:\n", "```python\n", "sales_data = pd.DataFrame({\n", " 'Region': ['East', 'West', 'East', 'West', 'East', 'West'],\n", " 'Category': ['Electronics', 'Electronics', 'Clothing', 'Clothing', 'Electronics', 'Clothing'],\n", " 'Revenue': [1200, 1500, 400, 600, 800, 750]\n", "})\n", "```\n", "Create a pivot table showing total (`sum`) Revenue with `'Region'` as rows and `'Category'` as columns. Add margin totals (`margins=True`)." ] }, { "cell_type": "code", "execution_count": null, "id": "7628dcff", "metadata": {}, "outputs": [], "source": [ "sales_data = pd.DataFrame({\n", " 'Region': ['East', 'West', 'East', 'West', 'East', 'West'],\n", " 'Category': ['Electronics', 'Electronics', 'Clothing', 'Clothing', 'Electronics', 'Clothing'],\n", " 'Revenue': [1200, 1500, 400, 600, 800, 750]\n", "})\n", "\n", "# Create pivot table\n" ] }, { "cell_type": "markdown", "id": "dd1d08c5", "metadata": {}, "source": [ "### Problem 9: Unpivoting Data with pd.melt()\n", "\n", "Given wide data where months are columns:\n", "```python\n", "wide_df = pd.DataFrame({\n", " 'Product': ['Laptop', 'Mouse'],\n", " 'Jan_Sales': [20, 150],\n", " 'Feb_Sales': [25, 180],\n", " 'Mar_Sales': [30, 210]\n", "})\n", "```\n", "Use `pd.melt()` to reshape this into a tidy table with columns: `'Product'`, `'Month'`, and `'Sales_Units'`." ] }, { "cell_type": "code", "execution_count": null, "id": "f3b3e2e5", "metadata": {}, "outputs": [], "source": [ "wide_df = pd.DataFrame({\n", " 'Product': ['Laptop', 'Mouse'],\n", " 'Jan_Sales': [20, 150],\n", " 'Feb_Sales': [25, 180],\n", " 'Mar_Sales': [30, 210]\n", "})\n", "\n", "# Melt into long format\n" ] }, { "cell_type": "markdown", "id": "d5a55b66", "metadata": {}, "source": [ "### Problem 10: Ranking Values with .rank()\n", "\n", "Given a leaderboard:\n", "```python\n", "runners = pd.DataFrame({\n", " 'Runner': ['Alex', 'Brian', 'Carlos', 'David', 'Evan'],\n", " 'Time_Sec': [54.2, 52.8, 56.1, 52.8, 58.0]\n", "})\n", "```\n", "Add a `'Rank'` column ranking runners from fastest (shortest time = Rank 1) to slowest, using `method='min'`." ] }, { "cell_type": "code", "execution_count": null, "id": "82259856", "metadata": {}, "outputs": [], "source": [ "runners = pd.DataFrame({\n", " 'Runner': ['Alex', 'Brian', 'Carlos', 'David', 'Evan'],\n", " 'Time_Sec': [54.2, 52.8, 56.1, 52.8, 58.0]\n", "})\n", "\n", "# Add Rank column\n" ] }, { "cell_type": "markdown", "id": "4536869d", "metadata": {}, "source": [ "### Problem 11: Cumulative Running Metrics (.cumsum & .cummax)\n", "\n", "Given daily revenue for a store:\n", "```python\n", "financials = pd.DataFrame({\n", " 'Day': [1, 2, 3, 4, 5],\n", " 'Daily_Revenue': [1000, 1500, 800, 2200, 1800]\n", "})\n", "```\n", "1. Add `'Running_Total'` showing cumulative sum of revenue.\n", "2. Add `'Peak_Daily_Revenue'` showing the highest single-day revenue observed up to that day." ] }, { "cell_type": "code", "execution_count": null, "id": "91372eed", "metadata": {}, "outputs": [], "source": [ "financials = pd.DataFrame({\n", " 'Day': [1, 2, 3, 4, 5],\n", " 'Daily_Revenue': [1000, 1500, 800, 2200, 1800]\n", "})\n", "\n", "# Compute cumulative metrics\n" ] }, { "cell_type": "markdown", "id": "a8b772ea", "metadata": {}, "source": [ "### Problem 12: Value Mapping with .map() and .replace()\n", "\n", "Given employee records with abbreviated department codes:\n", "```python\n", "staff = pd.DataFrame({\n", " 'Name': ['Liam', 'Emma', 'Noah', 'Olivia'],\n", " 'Dept_Code': ['HR', 'IT', 'ENG', 'HR']\n", "})\n", "```\n", "Use `.map()` with a dictionary `{'HR': 'Human Resources', 'IT': 'Information Tech', 'ENG': 'Engineering'}` to create `'Department_Full'`." ] }, { "cell_type": "code", "execution_count": null, "id": "d71609d3", "metadata": {}, "outputs": [], "source": [ "staff = pd.DataFrame({\n", " 'Name': ['Liam', 'Emma', 'Noah', 'Olivia'],\n", " 'Dept_Code': ['HR', 'IT', 'ENG', 'HR']\n", "})\n", "\n", "code_map = {'HR': 'Human Resources', 'IT': 'Information Tech', 'ENG': 'Engineering'}\n", "# Map Dept_Code to full name\n" ] }, { "cell_type": "markdown", "id": "a7b858c0", "metadata": {}, "source": [ "### Problem 13: Memory Optimization with Categorical Dtypes\n", "\n", "Create a DataFrame of 100,000 rows with a repetitive categorical column `'City'` randomly chosen from `['New York', 'London', 'Paris', 'Tokyo']`.\n", "1. Check memory usage with `.memory_usage(deep=True)`.\n", "2. Convert `'City'` to `category` dtype.\n", "3. Measure memory reduction." ] }, { "cell_type": "code", "execution_count": null, "id": "438a6922", "metadata": {}, "outputs": [], "source": [ "# Memory optimization with category\n" ] }, { "cell_type": "markdown", "id": "21524ddc", "metadata": {}, "source": [ "### Problem 14: Discretization & Binning with pd.cut()\n", "\n", "Given customer ages:\n", "```python\n", "ages_df = pd.DataFrame({\n", " 'Customer': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6'],\n", " 'Age': [16, 24, 38, 45, 62, 71]\n", "})\n", "```\n", "Use `pd.cut()` to segment `'Age'` into four bins: `[0, 18, 35, 60, 100]` with labels `['Youth', 'Young Adult', 'Middle Aged', 'Senior']`." ] }, { "cell_type": "code", "execution_count": null, "id": "6a479659", "metadata": {}, "outputs": [], "source": [ "ages_df = pd.DataFrame({\n", " 'Customer': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6'],\n", " 'Age': [16, 24, 38, 45, 62, 71]\n", "})\n", "\n", "# Bin ages with pd.cut\n" ] }, { "cell_type": "markdown", "id": "45b4d10c", "metadata": {}, "source": [ "### Problem 15: Fluent End-to-End Method Chaining Pipeline\n", "\n", "Given raw store orders:\n", "```python\n", "raw_orders = pd.DataFrame({\n", " 'Order_ID': [1, 2, 3, 4, 5],\n", " 'Status': ['Completed', 'Cancelled', 'Completed', 'Completed', 'Refunded'],\n", " 'Amount': [150.0, 20.0, 320.0, 85.0, 45.0],\n", " 'Tax_Exempt': [False, False, True, False, True]\n", "})\n", "```\n", "Build a single fluent chained expression (enclosed in parentheses) that:\n", "1. Filters for only `'Completed'` orders\n", "2. Adds a new column `'Tax'` ($10\\%$ of Amount if not Tax_Exempt, else $0$)\n", "3. Adds `'Total_Charge'` (Amount + Tax)\n", "4. Sorts by `'Total_Charge'` descending\n", "5. Resets the index" ] }, { "cell_type": "code", "execution_count": null, "id": "c99b6031", "metadata": {}, "outputs": [], "source": [ "raw_orders = pd.DataFrame({\n", " 'Order_ID': [1, 2, 3, 4, 5],\n", " 'Status': ['Completed', 'Cancelled', 'Completed', 'Completed', 'Refunded'],\n", " 'Amount': [150.0, 20.0, 320.0, 85.0, 45.0],\n", " 'Tax_Exempt': [False, False, True, False, True]\n", "})\n", "\n", "# Build method chaining pipeline\n" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }