{
"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",
" Employee | \n",
" Score | \n",
" Performance | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" Amy | \n",
" 92 | \n",
" Excellent | \n",
"
\n",
" \n",
" | 1 | \n",
" Brad | \n",
" 68 | \n",
" Needs Improvement | \n",
"
\n",
" \n",
" | 2 | \n",
" Chris | \n",
" 74 | \n",
" Satisfactory | \n",
"
\n",
" \n",
" | 3 | \n",
" Dana | \n",
" 85 | \n",
" Excellent | \n",
"
\n",
" \n",
" | 4 | \n",
" Eric | \n",
" 59 | \n",
" Needs Improvement | \n",
"
\n",
" \n",
"
\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",
" Tx_ID | \n",
" Customer | \n",
" Amount | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 101 | \n",
" Alice | \n",
" 50.0 | \n",
"
\n",
" \n",
" | 1 | \n",
" 102 | \n",
" Bob | \n",
" 75.0 | \n",
"
\n",
" \n",
" | 2 | \n",
" 103 | \n",
" Charlie | \n",
" 120.0 | \n",
"
\n",
" \n",
" | 3 | \n",
" 104 | \n",
" Alice | \n",
" 200.0 | \n",
"
\n",
" \n",
"
\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",
" Name | \n",
" Phone | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" John Doe | \n",
" 555-1234 | \n",
"
\n",
" \n",
" | 1 | \n",
" Jane Smith | \n",
" 555-5678 | \n",
"
\n",
" \n",
" | 2 | \n",
" Bob Johnson | \n",
" 555-9012 | \n",
"
\n",
" \n",
"
\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",
" User | \n",
" Start | \n",
" End | \n",
" Duration_Days | \n",
" Over_100_Days | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" UserA | \n",
" 2025-01-10 | \n",
" 2025-04-10 | \n",
" 90 | \n",
" False | \n",
"
\n",
" \n",
" | 1 | \n",
" UserB | \n",
" 2025-03-01 | \n",
" 2025-03-31 | \n",
" 30 | \n",
" False | \n",
"
\n",
" \n",
" | 2 | \n",
" UserC | \n",
" 2025-06-15 | \n",
" 2026-06-15 | \n",
" 365 | \n",
" True | \n",
"
\n",
" \n",
"
\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",
" Region | \n",
" Revenue | \n",
" Quarter | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" North | \n",
" 45000 | \n",
" Q1 | \n",
"
\n",
" \n",
" | 1 | \n",
" South | \n",
" 32000 | \n",
" Q1 | \n",
"
\n",
" \n",
" | 2 | \n",
" North | \n",
" 51000 | \n",
" Q2 | \n",
"
\n",
" \n",
" | 3 | \n",
" South | \n",
" 39000 | \n",
" Q2 | \n",
"
\n",
" \n",
"
\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",
" Emp_ID | \n",
" Name | \n",
" Dept_ID | \n",
" Dept_Name | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 1 | \n",
" Alice | \n",
" 10 | \n",
" Engineering | \n",
"
\n",
" \n",
" | 1 | \n",
" 2 | \n",
" Bob | \n",
" 20 | \n",
" Marketing | \n",
"
\n",
" \n",
" | 2 | \n",
" 3 | \n",
" Charlie | \n",
" 10 | \n",
" Engineering | \n",
"
\n",
" \n",
"
\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",
" Emp_ID | \n",
" Name | \n",
" Dept_ID | \n",
" Dept_Name | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 1 | \n",
" Alice | \n",
" 10 | \n",
" Engineering | \n",
"
\n",
" \n",
" | 1 | \n",
" 2 | \n",
" Bob | \n",
" 20 | \n",
" Marketing | \n",
"
\n",
" \n",
" | 2 | \n",
" 3 | \n",
" Charlie | \n",
" 10 | \n",
" Engineering | \n",
"
\n",
" \n",
" | 3 | \n",
" 4 | \n",
" Diana | \n",
" 30 | \n",
" NaN | \n",
"
\n",
" \n",
"
\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",
" Emp_ID | \n",
" Name | \n",
" Dept_ID | \n",
" Dept_Name | \n",
" _merge | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 1 | \n",
" Alice | \n",
" 10 | \n",
" Engineering | \n",
" both | \n",
"
\n",
" \n",
" | 1 | \n",
" 2 | \n",
" Bob | \n",
" 20 | \n",
" Marketing | \n",
" both | \n",
"
\n",
" \n",
" | 2 | \n",
" 3 | \n",
" Charlie | \n",
" 10 | \n",
" Engineering | \n",
" both | \n",
"
\n",
" \n",
" | 3 | \n",
" 4 | \n",
" Diana | \n",
" 30 | \n",
" NaN | \n",
" left_only | \n",
"
\n",
" \n",
"
\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",
" Emp_ID | \n",
" Name | \n",
" Dept_ID | \n",
"
\n",
" \n",
" \n",
" \n",
" | 3 | \n",
" 4 | \n",
" Diana | \n",
" 30 | \n",
"
\n",
" \n",
"
\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",
" | Category | \n",
" Clothing | \n",
" Electronics | \n",
" Total | \n",
"
\n",
" \n",
" | Region | \n",
" | \n",
" | \n",
" | \n",
"
\n",
" \n",
" \n",
" \n",
" | East | \n",
" 400 | \n",
" 2000 | \n",
" 2400 | \n",
"
\n",
" \n",
" | West | \n",
" 1350 | \n",
" 1500 | \n",
" 2850 | \n",
"
\n",
" \n",
" | Total | \n",
" 1750 | \n",
" 3500 | \n",
" 5250 | \n",
"
\n",
" \n",
"
\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",
" Product | \n",
" Month | \n",
" Sales_Units | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" Laptop | \n",
" Jan_Sales | \n",
" 20 | \n",
"
\n",
" \n",
" | 1 | \n",
" Mouse | \n",
" Jan_Sales | \n",
" 150 | \n",
"
\n",
" \n",
" | 2 | \n",
" Laptop | \n",
" Feb_Sales | \n",
" 25 | \n",
"
\n",
" \n",
" | 3 | \n",
" Mouse | \n",
" Feb_Sales | \n",
" 180 | \n",
"
\n",
" \n",
" | 4 | \n",
" Laptop | \n",
" Mar_Sales | \n",
" 30 | \n",
"
\n",
" \n",
" | 5 | \n",
" Mouse | \n",
" Mar_Sales | \n",
" 210 | \n",
"
\n",
" \n",
"
\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",
" Runner | \n",
" Time_Sec | \n",
" Rank | \n",
"
\n",
" \n",
" \n",
" \n",
" | 1 | \n",
" Brian | \n",
" 52.8 | \n",
" 1 | \n",
"
\n",
" \n",
" | 3 | \n",
" David | \n",
" 52.8 | \n",
" 1 | \n",
"
\n",
" \n",
" | 0 | \n",
" Alex | \n",
" 54.2 | \n",
" 3 | \n",
"
\n",
" \n",
" | 2 | \n",
" Carlos | \n",
" 56.1 | \n",
" 4 | \n",
"
\n",
" \n",
" | 4 | \n",
" Evan | \n",
" 58.0 | \n",
" 5 | \n",
"
\n",
" \n",
"
\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",
" Day | \n",
" Daily_Revenue | \n",
" Running_Total | \n",
" Peak_Daily_Revenue | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 1 | \n",
" 1000 | \n",
" 1000 | \n",
" 1000 | \n",
"
\n",
" \n",
" | 1 | \n",
" 2 | \n",
" 1500 | \n",
" 2500 | \n",
" 1500 | \n",
"
\n",
" \n",
" | 2 | \n",
" 3 | \n",
" 800 | \n",
" 3300 | \n",
" 1500 | \n",
"
\n",
" \n",
" | 3 | \n",
" 4 | \n",
" 2200 | \n",
" 5500 | \n",
" 2200 | \n",
"
\n",
" \n",
" | 4 | \n",
" 5 | \n",
" 1800 | \n",
" 7300 | \n",
" 2200 | \n",
"
\n",
" \n",
"
\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",
" Name | \n",
" Dept_Code | \n",
" Department_Full | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" Liam | \n",
" HR | \n",
" Human Resources | \n",
"
\n",
" \n",
" | 1 | \n",
" Emma | \n",
" IT | \n",
" Information Tech | \n",
"
\n",
" \n",
" | 2 | \n",
" Noah | \n",
" ENG | \n",
" Engineering | \n",
"
\n",
" \n",
" | 3 | \n",
" Olivia | \n",
" HR | \n",
" Human Resources | \n",
"
\n",
" \n",
"
\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",
" Customer | \n",
" Age | \n",
" Age_Group | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" C1 | \n",
" 16 | \n",
" Youth | \n",
"
\n",
" \n",
" | 1 | \n",
" C2 | \n",
" 24 | \n",
" Young Adult | \n",
"
\n",
" \n",
" | 2 | \n",
" C3 | \n",
" 38 | \n",
" Middle Aged | \n",
"
\n",
" \n",
" | 3 | \n",
" C4 | \n",
" 45 | \n",
" Middle Aged | \n",
"
\n",
" \n",
" | 4 | \n",
" C5 | \n",
" 62 | \n",
" Senior | \n",
"
\n",
" \n",
" | 5 | \n",
" C6 | \n",
" 71 | \n",
" Senior | \n",
"
\n",
" \n",
"
\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",
" Order_ID | \n",
" Status | \n",
" Amount | \n",
" Tax_Exempt | \n",
" Tax | \n",
" Total_Charge | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 3 | \n",
" Completed | \n",
" 320.0 | \n",
" True | \n",
" 0.0 | \n",
" 320.0 | \n",
"
\n",
" \n",
" | 1 | \n",
" 1 | \n",
" Completed | \n",
" 150.0 | \n",
" False | \n",
" 15.0 | \n",
" 165.0 | \n",
"
\n",
" \n",
" | 2 | \n",
" 4 | \n",
" Completed | \n",
" 85.0 | \n",
" False | \n",
" 8.5 | \n",
" 93.5 | \n",
"
\n",
" \n",
"
\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
}