{ "cells": [ { "cell_type": "markdown", "id": "724c1b5b", "metadata": {}, "source": [ "# 💡 Pandas Practice Exercise 2: Solutions & Walkthroughs\n", "\n", "This notebook contains **complete, verified solutions** for all 15 scenario challenges in `04_pandas_exercise_2.ipynb`.\n", "Every code cell is pre-executed with visible outputs for instant verification." ] }, { "cell_type": "code", "execution_count": 1, "id": "a847d73c", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:52.754084Z", "iopub.status.busy": "2026-10-03T05:00:52.753972Z", "iopub.status.idle": "2026-10-03T05:00:53.093545Z", "shell.execute_reply": "2026-10-03T05:00:53.093208Z" } }, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np" ] }, { "cell_type": "markdown", "id": "a82a6847", "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": 2, "id": "9037bbfe", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.095161Z", "iopub.status.busy": "2026-10-03T05:00:53.095022Z", "iopub.status.idle": "2026-10-03T05:00:53.102453Z", "shell.execute_reply": "2026-10-03T05:00:53.102136Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
EmployeeScorePerformance
0Amy92Excellent
1Brad68Needs Improvement
2Chris74Satisfactory
3Dana85Excellent
4Eric59Needs Improvement
\n", "
" ], "text/plain": [ " Employee Score Performance\n", "0 Amy 92 Excellent\n", "1 Brad 68 Needs Improvement\n", "2 Chris 74 Satisfactory\n", "3 Dana 85 Excellent\n", "4 Eric 59 Needs Improvement" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "df = pd.DataFrame({\n", " 'Employee': ['Amy', 'Brad', 'Chris', 'Dana', 'Eric'],\n", " 'Score': [92, 68, 74, 85, 59]\n", "})\n", "\n", "# Nested np.where\n", "df['Performance'] = np.where(\n", " df['Score'] >= 85, 'Excellent',\n", " np.where(df['Score'] >= 70, 'Satisfactory', 'Needs Improvement')\n", ")\n", "\n", "display(df)" ] }, { "cell_type": "markdown", "id": "877907f7", "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": 3, "id": "cdf0918c", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.103785Z", "iopub.status.busy": "2026-10-03T05:00:53.103680Z", "iopub.status.idle": "2026-10-03T05:00:53.111183Z", "shell.execute_reply": "2026-10-03T05:00:53.110922Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Duplicate rows boolean mask:\n", "0 False\n", "1 False\n", "2 True\n", "3 False\n", "4 False\n", "5 True\n", "dtype: bool\n", "\n", "Clean logs without duplicates:\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Tx_IDCustomerAmount
0101Alice50.0
1102Bob75.0
2103Charlie120.0
3104Alice200.0
\n", "
" ], "text/plain": [ " Tx_ID Customer Amount\n", "0 101 Alice 50.0\n", "1 102 Bob 75.0\n", "2 103 Charlie 120.0\n", "3 104 Alice 200.0" ] }, "metadata": {}, "output_type": "display_data" } ], "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", "print(\"Duplicate rows boolean mask:\")\n", "print(logs.duplicated())\n", "\n", "clean_logs = logs.drop_duplicates(keep='first').reset_index(drop=True)\n", "print(\"\\nClean logs without duplicates:\")\n", "display(clean_logs)" ] }, { "cell_type": "markdown", "id": "63a1c8a3", "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": 4, "id": "937900ba", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.112344Z", "iopub.status.busy": "2026-10-03T05:00:53.112256Z", "iopub.status.idle": "2026-10-03T05:00:53.115950Z", "shell.execute_reply": "2026-10-03T05:00:53.115665Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NamePhone
0John Doe555-1234
1Jane Smith555-5678
2Bob Johnson555-9012
\n", "
" ], "text/plain": [ " Name Phone\n", "0 John Doe 555-1234\n", "1 Jane Smith 555-5678\n", "2 Bob Johnson 555-9012" ] }, "metadata": {}, "output_type": "display_data" } ], "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", "pattern = r'^(?P.*?) \\((?P.*?)\\)'\n", "extracted = contacts['Raw_Contact'].str.extract(pattern)\n", "display(extracted)" ] }, { "cell_type": "markdown", "id": "162a3360", "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": 5, "id": "71e40762", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.117133Z", "iopub.status.busy": "2026-10-03T05:00:53.117045Z", "iopub.status.idle": "2026-10-03T05:00:53.123366Z", "shell.execute_reply": "2026-10-03T05:00:53.123128Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
UserStartEndDuration_DaysOver_100_Days
0UserA2025-01-102025-04-1090False
1UserB2025-03-012025-03-3130False
2UserC2025-06-152026-06-15365True
\n", "
" ], "text/plain": [ " User Start End Duration_Days Over_100_Days\n", "0 UserA 2025-01-10 2025-04-10 90 False\n", "1 UserB 2025-03-01 2025-03-31 30 False\n", "2 UserC 2025-06-15 2026-06-15 365 True" ] }, "metadata": {}, "output_type": "display_data" } ], "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", "subs['Start'] = pd.to_datetime(subs['Start'])\n", "subs['End'] = pd.to_datetime(subs['End'])\n", "\n", "subs['Duration_Days'] = (subs['End'] - subs['Start']).dt.days\n", "subs['Over_100_Days'] = subs['Duration_Days'] > 100\n", "\n", "display(subs)" ] }, { "cell_type": "markdown", "id": "e6d286b4", "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": 6, "id": "c14cbf22", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.124458Z", "iopub.status.busy": "2026-10-03T05:00:53.124372Z", "iopub.status.idle": "2026-10-03T05:00:53.128448Z", "shell.execute_reply": "2026-10-03T05:00:53.128205Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
RegionRevenueQuarter
0North45000Q1
1South32000Q1
2North51000Q2
3South39000Q2
\n", "
" ], "text/plain": [ " Region Revenue Quarter\n", "0 North 45000 Q1\n", "1 South 32000 Q1\n", "2 North 51000 Q2\n", "3 South 39000 Q2" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "q1 = pd.DataFrame({'Region': ['North', 'South'], 'Revenue': [45000, 32000]})\n", "q2 = pd.DataFrame({'Region': ['North', 'South'], 'Revenue': [51000, 39000]})\n", "\n", "q1['Quarter'] = 'Q1'\n", "q2['Quarter'] = 'Q2'\n", "\n", "combined_sales = pd.concat([q1, q2], ignore_index=True)\n", "display(combined_sales)" ] }, { "cell_type": "markdown", "id": "f1cb637a", "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": 7, "id": "8d9021c4", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.129652Z", "iopub.status.busy": "2026-10-03T05:00:53.129555Z", "iopub.status.idle": "2026-10-03T05:00:53.137807Z", "shell.execute_reply": "2026-10-03T05:00:53.137569Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Inner Join (Only matching departments):\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Emp_IDNameDept_IDDept_Name
01Alice10Engineering
12Bob20Marketing
23Charlie10Engineering
\n", "
" ], "text/plain": [ " Emp_ID Name Dept_ID Dept_Name\n", "0 1 Alice 10 Engineering\n", "1 2 Bob 20 Marketing\n", "2 3 Charlie 10 Engineering" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Left Join (All employees preserved):\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Emp_IDNameDept_IDDept_Name
01Alice10Engineering
12Bob20Marketing
23Charlie10Engineering
34Diana30NaN
\n", "
" ], "text/plain": [ " Emp_ID Name Dept_ID Dept_Name\n", "0 1 Alice 10 Engineering\n", "1 2 Bob 20 Marketing\n", "2 3 Charlie 10 Engineering\n", "3 4 Diana 30 NaN" ] }, "metadata": {}, "output_type": "display_data" } ], "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_res = pd.merge(employees, departments, on='Dept_ID', how='inner')\n", "print(\"Inner Join (Only matching departments):\")\n", "display(inner_res)\n", "\n", "left_res = pd.merge(employees, departments, on='Dept_ID', how='left')\n", "print(\"\\nLeft Join (All employees preserved):\")\n", "display(left_res)" ] }, { "cell_type": "markdown", "id": "c0fd4ece", "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": 8, "id": "07fc869b", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.138856Z", "iopub.status.busy": "2026-10-03T05:00:53.138772Z", "iopub.status.idle": "2026-10-03T05:00:53.147933Z", "shell.execute_reply": "2026-10-03T05:00:53.147572Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Merged with indicator:\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Emp_IDNameDept_IDDept_Name_merge
01Alice10Engineeringboth
12Bob20Marketingboth
23Charlie10Engineeringboth
34Diana30NaNleft_only
\n", "
" ], "text/plain": [ " Emp_ID Name Dept_ID Dept_Name _merge\n", "0 1 Alice 10 Engineering both\n", "1 2 Bob 20 Marketing both\n", "2 3 Charlie 10 Engineering both\n", "3 4 Diana 30 NaN left_only" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Employees without matching Department record:\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Emp_IDNameDept_ID
34Diana30
\n", "
" ], "text/plain": [ " Emp_ID Name Dept_ID\n", "3 4 Diana 30" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "merged_indicator = pd.merge(employees, departments, on='Dept_ID', how='left', indicator=True)\n", "print(\"Merged with indicator:\")\n", "display(merged_indicator)\n", "\n", "unmatched_employees = merged_indicator[merged_indicator['_merge'] == 'left_only']\n", "print(\"\\nEmployees without matching Department record:\")\n", "display(unmatched_employees[['Emp_ID', 'Name', 'Dept_ID']])" ] }, { "cell_type": "markdown", "id": "c735d54a", "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": 9, "id": "33401a3f", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.149222Z", "iopub.status.busy": "2026-10-03T05:00:53.149120Z", "iopub.status.idle": "2026-10-03T05:00:53.161774Z", "shell.execute_reply": "2026-10-03T05:00:53.161533Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
CategoryClothingElectronicsTotal
Region
East40020002400
West135015002850
Total175035005250
\n", "
" ], "text/plain": [ "Category Clothing Electronics Total\n", "Region \n", "East 400 2000 2400\n", "West 1350 1500 2850\n", "Total 1750 3500 5250" ] }, "metadata": {}, "output_type": "display_data" } ], "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", "pivot_res = sales_data.pivot_table(\n", " index='Region',\n", " columns='Category',\n", " values='Revenue',\n", " aggfunc='sum',\n", " margins=True,\n", " margins_name='Total'\n", ")\n", "\n", "display(pivot_res)" ] }, { "cell_type": "markdown", "id": "16afb360", "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": 10, "id": "963e1a55", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.162934Z", "iopub.status.busy": "2026-10-03T05:00:53.162837Z", "iopub.status.idle": "2026-10-03T05:00:53.167521Z", "shell.execute_reply": "2026-10-03T05:00:53.167263Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ProductMonthSales_Units
0LaptopJan_Sales20
1MouseJan_Sales150
2LaptopFeb_Sales25
3MouseFeb_Sales180
4LaptopMar_Sales30
5MouseMar_Sales210
\n", "
" ], "text/plain": [ " Product Month Sales_Units\n", "0 Laptop Jan_Sales 20\n", "1 Mouse Jan_Sales 150\n", "2 Laptop Feb_Sales 25\n", "3 Mouse Feb_Sales 180\n", "4 Laptop Mar_Sales 30\n", "5 Mouse Mar_Sales 210" ] }, "metadata": {}, "output_type": "display_data" } ], "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", "long_df = pd.melt(\n", " wide_df,\n", " id_vars=['Product'],\n", " value_vars=['Jan_Sales', 'Feb_Sales', 'Mar_Sales'],\n", " var_name='Month',\n", " value_name='Sales_Units'\n", ")\n", "\n", "display(long_df)" ] }, { "cell_type": "markdown", "id": "9e831987", "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": 11, "id": "09e91bd7", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.168646Z", "iopub.status.busy": "2026-10-03T05:00:53.168555Z", "iopub.status.idle": "2026-10-03T05:00:53.173510Z", "shell.execute_reply": "2026-10-03T05:00:53.173289Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
RunnerTime_SecRank
1Brian52.81
3David52.81
0Alex54.23
2Carlos56.14
4Evan58.05
\n", "
" ], "text/plain": [ " Runner Time_Sec Rank\n", "1 Brian 52.8 1\n", "3 David 52.8 1\n", "0 Alex 54.2 3\n", "2 Carlos 56.1 4\n", "4 Evan 58.0 5" ] }, "metadata": {}, "output_type": "display_data" } ], "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", "runners['Rank'] = runners['Time_Sec'].rank(ascending=True, method='min').astype(int)\n", "runners = runners.sort_values(by='Rank')\n", "display(runners)" ] }, { "cell_type": "markdown", "id": "e986589b", "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": 12, "id": "555b6436", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.174571Z", "iopub.status.busy": "2026-10-03T05:00:53.174481Z", "iopub.status.idle": "2026-10-03T05:00:53.178049Z", "shell.execute_reply": "2026-10-03T05:00:53.177836Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
DayDaily_RevenueRunning_TotalPeak_Daily_Revenue
01100010001000
12150025001500
2380033001500
34220055002200
45180073002200
\n", "
" ], "text/plain": [ " Day Daily_Revenue Running_Total Peak_Daily_Revenue\n", "0 1 1000 1000 1000\n", "1 2 1500 2500 1500\n", "2 3 800 3300 1500\n", "3 4 2200 5500 2200\n", "4 5 1800 7300 2200" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "financials = pd.DataFrame({\n", " 'Day': [1, 2, 3, 4, 5],\n", " 'Daily_Revenue': [1000, 1500, 800, 2200, 1800]\n", "})\n", "\n", "financials['Running_Total'] = financials['Daily_Revenue'].cumsum()\n", "financials['Peak_Daily_Revenue'] = financials['Daily_Revenue'].cummax()\n", "\n", "display(financials)" ] }, { "cell_type": "markdown", "id": "b20fe279", "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": 13, "id": "c8481e94", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.179178Z", "iopub.status.busy": "2026-10-03T05:00:53.179090Z", "iopub.status.idle": "2026-10-03T05:00:53.182801Z", "shell.execute_reply": "2026-10-03T05:00:53.182563Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NameDept_CodeDepartment_Full
0LiamHRHuman Resources
1EmmaITInformation Tech
2NoahENGEngineering
3OliviaHRHuman Resources
\n", "
" ], "text/plain": [ " Name Dept_Code Department_Full\n", "0 Liam HR Human Resources\n", "1 Emma IT Information Tech\n", "2 Noah ENG Engineering\n", "3 Olivia HR Human Resources" ] }, "metadata": {}, "output_type": "display_data" } ], "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", "staff['Department_Full'] = staff['Dept_Code'].map(code_map)\n", "\n", "display(staff)" ] }, { "cell_type": "markdown", "id": "71afd27a", "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": 14, "id": "915080be", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.183895Z", "iopub.status.busy": "2026-10-03T05:00:53.183807Z", "iopub.status.idle": "2026-10-03T05:00:53.213946Z", "shell.execute_reply": "2026-10-03T05:00:53.213663Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Memory before (object): 5,499,476 bytes\n", "Memory after (category): 100,352 bytes\n", "Reduction: 54.8x smaller!\n" ] } ], "source": [ "n_rows = 100_000\n", "cities = np.random.choice(['New York', 'London', 'Paris', 'Tokyo'], size=n_rows)\n", "df_large = pd.DataFrame({'City': cities})\n", "\n", "mem_before = df_large['City'].memory_usage(deep=True)\n", "df_large['City'] = df_large['City'].astype('category')\n", "mem_after = df_large['City'].memory_usage(deep=True)\n", "\n", "print(f\"Memory before (object): {mem_before:>10,} bytes\")\n", "print(f\"Memory after (category): {mem_after:>10,} bytes\")\n", "print(f\"Reduction: {mem_before / mem_after:.1f}x smaller!\")" ] }, { "cell_type": "markdown", "id": "ff84bee0", "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": 15, "id": "1d74bd7a", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.215175Z", "iopub.status.busy": "2026-10-03T05:00:53.215078Z", "iopub.status.idle": "2026-10-03T05:00:53.219637Z", "shell.execute_reply": "2026-10-03T05:00:53.219358Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
CustomerAgeAge_Group
0C116Youth
1C224Young Adult
2C338Middle Aged
3C445Middle Aged
4C562Senior
5C671Senior
\n", "
" ], "text/plain": [ " Customer Age Age_Group\n", "0 C1 16 Youth\n", "1 C2 24 Young Adult\n", "2 C3 38 Middle Aged\n", "3 C4 45 Middle Aged\n", "4 C5 62 Senior\n", "5 C6 71 Senior" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "ages_df = pd.DataFrame({\n", " 'Customer': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6'],\n", " 'Age': [16, 24, 38, 45, 62, 71]\n", "})\n", "\n", "bins = [0, 18, 35, 60, 100]\n", "labels = ['Youth', 'Young Adult', 'Middle Aged', 'Senior']\n", "\n", "ages_df['Age_Group'] = pd.cut(ages_df['Age'], bins=bins, labels=labels)\n", "display(ages_df)" ] }, { "cell_type": "markdown", "id": "4f23b2f4", "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": 16, "id": "58b3a062", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:00:53.220790Z", "iopub.status.busy": "2026-10-03T05:00:53.220701Z", "iopub.status.idle": "2026-10-03T05:00:53.226738Z", "shell.execute_reply": "2026-10-03T05:00:53.226489Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Order_IDStatusAmountTax_ExemptTaxTotal_Charge
03Completed320.0True0.0320.0
11Completed150.0False15.0165.0
24Completed85.0False8.593.5
\n", "
" ], "text/plain": [ " Order_ID Status Amount Tax_Exempt Tax Total_Charge\n", "0 3 Completed 320.0 True 0.0 320.0\n", "1 1 Completed 150.0 False 15.0 165.0\n", "2 4 Completed 85.0 False 8.5 93.5" ] }, "metadata": {}, "output_type": "display_data" } ], "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", "clean_pipeline = (\n", " raw_orders\n", " .query(\"Status == 'Completed'\")\n", " .assign(\n", " Tax=lambda d: np.where(d['Tax_Exempt'], 0.0, d['Amount'] * 0.10),\n", " Total_Charge=lambda d: d['Amount'] + d['Tax']\n", " )\n", " .sort_values(by='Total_Charge', ascending=False)\n", " .reset_index(drop=True)\n", ")\n", "\n", "display(clean_pipeline)" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.11" } }, "nbformat": 4, "nbformat_minor": 5 }