{ "cells": [ { "cell_type": "markdown", "id": "1b86e73f", "metadata": {}, "source": [ "# 🐼 The Easy Pandas Guide: From Zero to Data Masterclass\n", "> **A Comprehensive, Friendly, and Deeply Detailed Reference Guide to Tabular Data**\n", "> \n", "> *Target Audience:* Beginners looking for crystal-clear clarity, Data Analysts transitioning from Excel/SQL, and ML Engineers engineering clean tabular features.\n", "\n", "---\n", "\n", "### 🌟 How to Use This Notebook\n", "1. **Detailed Text & Explanations:** Every single concept is explained thoroughly in plain English, with detailed background context, intuitive analogies, and \"under-the-hood\" mechanics.\n", "2. **Visual Mental Models:** Comprehensive ASCII diagrams illustrate how Series, DataFrames, Indexing, and the GroupBy Split-Apply-Combine engine work.\n", "3. **Pre-Executed & Verified:** Every code cell is pre-executed with real outputs so you can read this like an illustrated technical book or run each cell interactively to experiment.\n", "4. **Pro-Tips, Gotchas & Best Practices:** Dedicated callout blocks highlight real-world gotchas like `SettingWithCopyWarning`, NaN comparisons, and memory optimization.\n", "5. **Smooth Navigation:** Use the **Table of Contents** below or each chapter's `[⬆️ Back to Table of Contents]` link to jump directly to any section.\n", "\n", "---\n", "\n", "\n", "## 📑 Table of Contents\n", "\n", "| Part | Chapter | Key Topics Covered |\n", "| :---: | :--- | :--- |\n", "| **I** | [1. Core Mental Model: What is Pandas?](#ch1) | Python Lists vs NumPy vs Pandas, DataFrame Anatomy, Hash-table Indexing |\n", "| **I** | [2. Creating Series & DataFrames](#ch2) | From Lists, Dictionaries, NumPy Arrays; Custom Indices, Automatic Alignment |\n", "| **I** | [3. Reading, Writing & Inspecting Data](#ch3) | CSV, Excel, Parquet, JSON; `head()`, `info()`, `describe()`, memory usage |\n", "| **II** | [4. Selection & Slicing: loc vs iloc](#ch4) | `[]` syntax, `iloc` (position) vs `loc` (labels), boundary rules, scalar `.at`/`.iat` |\n", "| **II** | [5. Filtering & Boolean Queries](#ch5) | Conditions (`&`, `\\|`, `~`), `.isin()`, `.between()`, `.query()`, avoiding `and`/`or` |\n", "| **III** | [6. Modifying: Adding, Renaming & Dropping](#ch6) | Vectorized column creation, `.assign()`, `.rename()`, `.drop()`, axis model |\n", "| **III** | [7. Handling Missing Data (NaNs)](#ch7) | `np.nan` mechanics, `.isna()`, `.notna()`, `.dropna()`, `.fillna()`, imputation |\n", "| **III** | [8. Sorting, Ranking & Index Manipulation](#ch8) | `.sort_values()`, multi-column sort, `.rank()`, `.reset_index()`, `.set_index()` |\n", "| **IV** | [9. Summary Statistics & Frequencies](#ch9) | Aggregations, `.value_counts()`, `.nunique()`, correlation `.corr()` |\n", "| **IV** | [10. The GroupBy Engine (Split-Apply-Combine)](#ch10) | Mental model, `.agg()`, multi-level aggregations, `.transform()`, `.filter()` |\n", "| **V** | [11. Text & String Operations (`.str`)](#ch11) | Cleaning whitespace, case changes, regex pattern matching, `.split(expand=True)` |\n", "| **V** | [12. Working with Dates & Times (`.dt`)](#ch12) | `pd.to_datetime()`, calendar properties, elapsed time, filtering date ranges |\n", "| **V** | [13. Combining Datasets: Concat & Merge](#ch13) | Stacking (`concat`), SQL joins (`merge`: inner, left, right, outer, anti-join) |\n", "| **V** | [14. Reshaping: Pivot Tables & Melt](#ch14) | Cross-tabulations with `pivot_table()`, unpivoting wide data with `melt()` |\n", "| **V** | [15. Performance, Gotchas & Cheat Sheet](#ch15) | `SettingWithCopyWarning`, vectorization benchmark vs loops, categorical dtypes |" ] }, { "cell_type": "markdown", "id": "94798172", "metadata": {}, "source": [ "\n", "---\n", "# Part I: Foundations & Mental Models\n", "\n", "## 1. Core Mental Model: What is Pandas?\n", "\n", "In scientific and business computing, data rarely arrives as a clean, uniform matrix of floating-point numbers. Instead, real-world data is **heterogeneous** and **tabular**:\n", "- A single record might contain a person's **name** (text), **age** (integer), **salary** (floating-point), **hire date** (datetime), and **department** (category).\n", "- Rows represent individual entities (e.g., customers, transactions, sensor readings).\n", "- Columns represent variables or attributes measured for each entity.\n", "\n", "### 1.1 Python Lists vs. NumPy ndarrays vs. Pandas DataFrames\n", "To appreciate why Pandas is the universal standard for tabular data, let's contrast how Python tools handle data:\n", "\n", "| Feature | Standard Python List of Dicts | NumPy ndarray | Pandas DataFrame |\n", "| :--- | :--- | :--- | :--- |\n", "| **Data Types** | Mixed (dynamic types) | Homogeneous (single dtype across entire array) | Heterogeneous (each column has its own dtype) |\n", "| **Row / Column Labels** | No native labels; manual dictionary key lookups | Integer positions only `[0, 1, 2]` | Dual-axis labels: named columns AND indexed rows |\n", "| **Speed & Vectorization** | Slow; requires Python `for` loops | Blazing fast; contiguous C/SIMD arrays | Blazing fast; built directly on top of NumPy |\n", "| **Missing Data Support** | Manual `None` checks | `np.nan` (floats only; clumsy for strings/ints) | First-class null handling across all types |\n", "| **Relational Operations** | Complex custom nested loops | Not supported natively | SQL-like Joins, Merges, GroupBys, Pivot Tables |\n", "\n", "### 1.2 The Anatomy of a DataFrame\n", "A Pandas **DataFrame** is a 2-dimensional labeled data structure composed of three interconnected parts:\n", "1. **The Index (Row Labels):** Metadata identifying each row (e.g., 0, 1, 2 or customer IDs like `'CUST-001'`).\n", "2. **The Columns (Feature Labels):** Metadata identifying each variable (e.g., `'Name'`, `'Salary'`).\n", "3. **The Series (Column Data):** Each column is a 1-dimensional **`pd.Series`** containing the actual data buffer.\n", "\n", "```\n", " COLUMNS (Variables)\n", " 'Name' 'Age' 'Department' 'Salary'\n", " +---------------+-------------+--------------------+--------------+\n", " Index 0 ----> | Alice | 25 | HR | 60,000.0 | \\\n", " Index 1 ----> | Bob | 30 | IT | 85,000.0 | |-- ROWS\n", " Index 2 ----> | Charlie | 35 | Marketing | 72,000.0 | / (Records)\n", " +---------------+-------------+--------------------+--------------+\n", " pd.Series pd.Series pd.Series pd.Series\n", " dtype: object dtype: int64 dtype: object dtype: float64\n", "```\n", "\n", "### 1.3 Under the Hood: The Index Hash Map\n", "Why does Pandas have an **Index** instead of just using plain row numbers?\n", "- Under the hood, the Pandas Index is implemented using an efficient hash table.\n", "- When you look up a row by its label (e.g., `df.loc['CUST-104']`), Pandas does not scan rows one by one in $O(N)$ time. Instead, it performs an instant $O(1)$ hash map lookup to locate the exact memory offset of that record!" ] }, { "cell_type": "code", "execution_count": 4, "id": "7d240e42", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.102848Z", "iopub.status.busy": "2026-10-03T05:03:26.102567Z", "iopub.status.idle": "2026-10-03T05:03:26.529265Z", "shell.execute_reply": "2026-10-03T05:03:26.528914Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Pandas Version: 3.0.6\n", "NumPy Version: 2.5.3\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "\n", "print(f\"Pandas Version: {pd.__version__}\")\n", "print(f\"NumPy Version: {np.__version__}\")" ] }, { "cell_type": "markdown", "id": "5a23930b", "metadata": {}, "source": [ "\n", "---\n", "## 2. Creating Series & DataFrames from Scratch\n", "\n", "Before loading massive external CSV or database files, mastering how to construct Series and DataFrames from native Python objects is essential for creating test cases, mocking data, and converting computation outputs.\n", "\n", "### 2.1 The `pd.Series`: 1D Labeled Array\n", "A `Series` is the foundational building block of Pandas. Think of it as a 1D NumPy array with a labeled index.\n", "- If you don't supply an index, Pandas automatically assigns a default `RangeIndex` starting at `0, 1, 2, ...`.\n", "- If you supply custom labels, you can access elements using both the label name and its zero-based integer position." ] }, { "cell_type": "code", "execution_count": 5, "id": "2497b1d3", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.530790Z", "iopub.status.busy": "2026-10-03T05:03:26.530633Z", "iopub.status.idle": "2026-10-03T05:03:26.537707Z", "shell.execute_reply": "2026-10-03T05:03:26.537382Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Series with default RangeIndex:\n", "0 22.5\n", "1 24.0\n", "2 19.8\n", "3 25.2\n", "4 21.0\n", "Name: Temperature_C, dtype: float64\n", "\n", "Series with custom day labels:\n", "Mon 22.5\n", "Tue 24.0\n", "Wed 19.8\n", "Thu 25.2\n", "Fri 21.0\n", "Name: Daily_Temp, dtype: float64\n", "\n", "Wednesday's temp (by label): 19.8°C\n", "First day's temp (by position): 22.5°C\n" ] } ], "source": [ "# 1. Series from a Python list with default integer index\n", "temperatures = pd.Series([22.5, 24.0, 19.8, 25.2, 21.0], name='Temperature_C')\n", "print(\"Series with default RangeIndex:\")\n", "print(temperatures)\n", "\n", "# 2. Series with custom index labels (e.g. Days of the week)\n", "days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']\n", "weekly_temps = pd.Series([22.5, 24.0, 19.8, 25.2, 21.0], index=days, name='Daily_Temp')\n", "print(\"\\nSeries with custom day labels:\")\n", "print(weekly_temps)\n", "\n", "# Lookups: By label and by position\n", "print(f\"\\nWednesday's temp (by label): {weekly_temps['Wed']}°C\")\n", "print(f\"First day's temp (by position): {weekly_temps.iloc[0]}°C\")" ] }, { "cell_type": "markdown", "id": "65d59e05", "metadata": {}, "source": [ "### 2.2 Automatic Index Alignment: A Series Superpower\n", "One of the most powerful and unique features of Pandas is **automatic index alignment**.\n", "When performing arithmetic on two Series (like addition, subtraction, or multiplication), Pandas does **not** simply pair elements by their physical order. Instead, it automatically matches elements by their **index labels**!\n", "If an index label exists in one Series but not the other, Pandas gracefully inserts `NaN` (Not a Number) to prevent silent misalignments." ] }, { "cell_type": "code", "execution_count": 6, "id": "9b12194e", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.538985Z", "iopub.status.busy": "2026-10-03T05:03:26.538887Z", "iopub.status.idle": "2026-10-03T05:03:26.544488Z", "shell.execute_reply": "2026-10-03T05:03:26.544190Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Week 1 Sales:\n", " Apples 50\n", "Bananas 30\n", "Cherries 20\n", "dtype: int64\n", "\n", "Week 2 Sales:\n", " Bananas 45\n", "Apples 60\n", "Dates 15\n", "dtype: int64\n", "\n", "Total Combined Sales (Notice automatic alignment & NaN for unmatched):\n", "Apples 110.0\n", "Bananas 75.0\n", "Cherries NaN\n", "Dates NaN\n", "dtype: float64\n" ] } ], "source": [ "# Sales in Week 1 and Week 2 with different product assortments\n", "week1 = pd.Series({'Apples': 50, 'Bananas': 30, 'Cherries': 20})\n", "week2 = pd.Series({'Bananas': 45, 'Apples': 60, 'Dates': 15})\n", "\n", "print(\"Week 1 Sales:\\n\", week1)\n", "print(\"\\nWeek 2 Sales:\\n\", week2)\n", "\n", "# Vectorized addition aligns by product name automatically!\n", "total_sales = week1 + week2\n", "print(\"\\nTotal Combined Sales (Notice automatic alignment & NaN for unmatched):\")\n", "print(total_sales)" ] }, { "cell_type": "markdown", "id": "d007e90c", "metadata": {}, "source": [ "### 2.3 Creating a `pd.DataFrame`\n", "There are several intuitive ways to create a DataFrame:\n", "\n", "#### Method A: Dictionary of Lists (Column-Oriented)\n", "This is the most common format: keys become column headers, and list values become column elements. All lists must have identical lengths." ] }, { "cell_type": "code", "execution_count": 64, "id": "3a879652", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.545640Z", "iopub.status.busy": "2026-10-03T05:03:26.545537Z", "iopub.status.idle": "2026-10-03T05:03:26.553448Z", "shell.execute_reply": "2026-10-03T05:03:26.553113Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DataFrame created from Dictionary of Lists:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
0101Alice SmithHR620003True
1102Bob JonesIT880007True
2103Charlie BrownMarketing710004False
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "0 101 Alice Smith HR 62000 3 True\n", "1 102 Bob Jones IT 88000 7 True\n", "2 103 Charlie Brown Marketing 71000 4 False" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Method A: Dictionary of Lists\n", "staff_data = {\n", " 'Emp_ID': [101, 102, 103, 104, 105],\n", " 'Name': ['Alice Smith', 'Bob Jones', 'Charlie Brown', 'Diana Prince', 'Evan Wright'],\n", " 'Department': ['HR', 'IT', 'Marketing', 'IT', 'Finance'],\n", " 'Salary': [62000, 88000, 71000, 94000, 105000],\n", " 'Years_Experience': [3, 7, 4, 9, 12],\n", " 'Is_Remote': [True, True, False, False, True]\n", "}\n", "\n", "df_staff = pd.DataFrame(staff_data)\n", "print(\"DataFrame created from Dictionary of Lists:\")\n", "# display(df_staff)\n", "df_staff.head(3) # it will show the frist n row\n", "#print(df_staff.columns)" ] }, { "cell_type": "markdown", "id": "f2838549", "metadata": {}, "source": [ "#### Method B: List of Dictionaries (Row-Oriented)\n", "This format mirrors records returned by REST APIs, JSON files, or database queries where each item represents an individual record." ] }, { "cell_type": "code", "execution_count": 8, "id": "f4a22ebd", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.554704Z", "iopub.status.busy": "2026-10-03T05:03:26.554605Z", "iopub.status.idle": "2026-10-03T05:03:26.558726Z", "shell.execute_reply": "2026-10-03T05:03:26.558460Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DataFrame created from List of Dictionaries (API/JSON format):\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", "
CityCountryPopulation_M
0New YorkUSA8.3
1TokyoJapan13.9
2ParisFrance2.1
\n", "
" ], "text/plain": [ " City Country Population_M\n", "0 New York USA 8.3\n", "1 Tokyo Japan 13.9\n", "2 Paris France 2.1" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Method B: List of Dictionaries (Row-oriented)\n", "api_records = [\n", " {'City': 'New York', 'Country': 'USA', 'Population_M': 8.3},\n", " {'City': 'Tokyo', 'Country': 'Japan', 'Population_M': 13.9},\n", " {'City': 'Paris', 'Country': 'France', 'Population_M': 2.1}\n", "]\n", "\n", "df_cities = pd.DataFrame(api_records)\n", "print(\"DataFrame created from List of Dictionaries (API/JSON format):\")\n", "display(df_cities)" ] }, { "cell_type": "markdown", "id": "f0293a42", "metadata": {}, "source": [ "#### Method C: From a 2D NumPy Array\n", "When converting matrix computations into a labeled table, provide explicit `columns` and `index` arguments:" ] }, { "cell_type": "code", "execution_count": 9, "id": "6dca5dc1", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.559898Z", "iopub.status.busy": "2026-10-03T05:03:26.559802Z", "iopub.status.idle": "2026-10-03T05:03:26.564152Z", "shell.execute_reply": "2026-10-03T05:03:26.563913Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DataFrame created from 2D NumPy Array:\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", "
Feature_AFeature_BFeature_C
Sample_1612481
Sample_2703092
Sample_3968484
Sample_4973312
\n", "
" ], "text/plain": [ " Feature_A Feature_B Feature_C\n", "Sample_1 61 24 81\n", "Sample_2 70 30 92\n", "Sample_3 96 84 84\n", "Sample_4 97 33 12" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Method C: From 2D NumPy array\n", "np.random.seed(42)\n", "matrix = np.random.randint(10, 100, size=(4, 3))\n", "\n", "df_matrix = pd.DataFrame(\n", " matrix,\n", " columns=['Feature_A', 'Feature_B', 'Feature_C'],\n", " index=['Sample_1', 'Sample_2', 'Sample_3', 'Sample_4']\n", ")\n", "print(\"DataFrame created from 2D NumPy Array:\")\n", "display(df_matrix)" ] }, { "cell_type": "markdown", "id": "10aa0690", "metadata": {}, "source": [ "### 2.4 DataFrame Anatomy & Structural Attributes\n", "Once a DataFrame is created, you can inspect its structural attributes without parentheses:\n", "- **`.shape`**: A tuple `(n_rows, n_columns)`.\n", "- **`.columns`**: An `Index` object containing column names.\n", "- **`.index`**: An `Index` object containing row labels.\n", "- **`.dtypes`**: The data type assigned to each column.\n", "- **`.ndim`**: The dimensionality (always `2` for a DataFrame, `1` for a Series).\n", "- **`.size`**: Total number of cells (`rows * columns`)." ] }, { "cell_type": "code", "execution_count": 10, "id": "8aa0cd68", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.565240Z", "iopub.status.busy": "2026-10-03T05:03:26.565154Z", "iopub.status.idle": "2026-10-03T05:03:26.567640Z", "shell.execute_reply": "2026-10-03T05:03:26.567410Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape (rows, cols): (5, 6)\n", "Total cells: 30\n", "Dimensions: 2\n", "Columns: ['Emp_ID', 'Name', 'Department', 'Salary', 'Years_Experience', 'Is_Remote']\n", "Row Index: RangeIndex(start=0, stop=5, step=1)\n", "\n", "Column Data Types:\n", "Emp_ID int64\n", "Name str\n", "Department str\n", "Salary int64\n", "Years_Experience int64\n", "Is_Remote bool\n", "dtype: object\n" ] } ], "source": [ "print(f\"Shape (rows, cols): {df_staff.shape}\")\n", "print(f\"Total cells: {df_staff.size}\")\n", "print(f\"Dimensions: {df_staff.ndim}\")\n", "print(f\"Columns: {list(df_staff.columns)}\")\n", "print(f\"Row Index: {df_staff.index}\")\n", "print(\"\\nColumn Data Types:\")\n", "print(df_staff.dtypes)" ] }, { "cell_type": "markdown", "id": "3ef3cd02", "metadata": {}, "source": [ "> 💡 **Key Takeaway:**\n", "> Every DataFrame is a collection of Series. Each column is homogeneous (one dtype), but the DataFrame as a whole is heterogeneous (contains diverse dtypes).\n", ">\n", "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "2ad3e0d7", "metadata": {}, "source": [ "\n", "---\n", "## 3. Reading, Writing & Inspecting Data\n", "\n", "In professional workflows, over 95% of datasets are imported from external storage: CSV files, Excel spreadsheets, SQL databases, Parquet files, or Cloud Object Stores.\n", "\n", "### 3.1 Common I/O Functions in Pandas\n", "Pandas provides bidirectional readers and writers for virtually every data format:\n", "\n", "| Format | Read Function | Write Function | Key Advantages & Notes |\n", "| :--- | :--- | :--- | :--- |\n", "| **CSV** | `pd.read_csv()` | `df.to_csv()` | Universal, human-readable text format. |\n", "| **Excel** | `pd.read_excel()` | `df.to_excel()` | Supports multi-sheet `.xlsx` workbooks. |\n", "| **Parquet** | `pd.read_parquet()` | `df.to_parquet()` | Fast, columnar, compressed binary; ideal for Big Data & ML. |\n", "| **JSON** | `pd.read_json()` | `df.to_json()` | Standard web format; handles nested dictionaries. |\n", "| **SQL** | `pd.read_sql()` | `df.to_sql()` | Connects directly to PostgreSQL, MySQL, SQLite, etc. |\n", "\n", "### 3.2 Key Arguments in `pd.read_csv()`\n", "Understanding these arguments avoids common parsing headaches:\n", "- `filepath_or_buffer`: Path to local file or URL.\n", "- `sep` or `delimiter`: Character separating values (default is `','`, use `'\\t'` for tab-separated).\n", "- `index_col`: Column to use as the row index (e.g., `index_col='User_ID'`).\n", "- `usecols`: List of specific columns to load (saves memory when files have 100+ columns).\n", "- `parse_dates`: List of column names to parse directly as datetimes instead of plain strings.\n", "- `na_values`: Additional strings to interpret as `NaN` (e.g. `['N/A', 'missing', '-999']`).\n", "- `chunksize`: Number of rows to read per iteration when processing files larger than system RAM." ] }, { "cell_type": "code", "execution_count": 11, "id": "d7c84f84", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.568836Z", "iopub.status.busy": "2026-10-03T05:03:26.568741Z", "iopub.status.idle": "2026-10-03T05:03:26.582649Z", "shell.execute_reply": "2026-10-03T05:03:26.582389Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exported staff data to staff_sample.csv successfully!\n", "Reloaded DataFrame from CSV:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
0101Alice SmithHR620003True
1102Bob JonesIT880007True
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "0 101 Alice Smith HR 62000 3 True\n", "1 102 Bob Jones IT 88000 7 True" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Export df_staff to a CSV file to demonstrate file I/O\n", "csv_filename = \"staff_sample.csv\"\n", "df_staff.to_csv(csv_filename, index=False)\n", "print(f\"Exported staff data to {csv_filename} successfully!\")\n", "\n", "# Read it back with specific parameters\n", "loaded_df = pd.read_csv(csv_filename)\n", "print(\"Reloaded DataFrame from CSV:\")\n", "display(loaded_df.head(2))\n", "\n", "# Clean up temporary file\n", "import os\n", "if os.path.exists(csv_filename):\n", " os.remove(csv_filename)" ] }, { "cell_type": "markdown", "id": "27c8f61f", "metadata": {}, "source": [ "### 3.3 Exploratory Data Inspection: First Look at Any Dataset\n", "Whenever you receive a dataset, always execute these inspection methods first:\n", "\n", "1. **`df.head(n)`**: Displays the first $n$ rows (default is 5). Verifies column headers and initial values.\n", "2. **`df.tail(n)`**: Displays the last $n$ rows. Useful to check for corrupted final rows or trailing summaries.\n", "3. **`df.sample(n)`**: Displays $n$ random rows. Prevents bias if data is sorted.\n", "4. **`df.info()`**: Comprehensive technical summary: total rows, column names, non-null counts, dtypes, and memory usage.\n", "5. **`df.describe()`**: Statistical summary of numeric distributions (mean, std, min, quartiles, max)." ] }, { "cell_type": "code", "execution_count": 12, "id": "048aecf6", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.583810Z", "iopub.status.busy": "2026-10-03T05:03:26.583709Z", "iopub.status.idle": "2026-10-03T05:03:26.592853Z", "shell.execute_reply": "2026-10-03T05:03:26.592589Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--- Head (First 3 rows) ---\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
0101Alice SmithHR620003True
1102Bob JonesIT880007True
2103Charlie BrownMarketing710004False
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "0 101 Alice Smith HR 62000 3 True\n", "1 102 Bob Jones IT 88000 7 True\n", "2 103 Charlie Brown Marketing 71000 4 False" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "--- Tail (Last 2 rows) ---\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
3104Diana PrinceIT940009False
4105Evan WrightFinance10500012True
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "3 104 Diana Prince IT 94000 9 False\n", "4 105 Evan Wright Finance 105000 12 True" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "--- Random Sample (2 rows) ---\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
1102Bob JonesIT880007True
4105Evan WrightFinance10500012True
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "1 102 Bob Jones IT 88000 7 True\n", "4 105 Evan Wright Finance 105000 12 True" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# 1. Preview head, tail, and random sample\n", "print(\"--- Head (First 3 rows) ---\")\n", "display(df_staff.head(3))\n", "\n", "print(\"\\n--- Tail (Last 2 rows) ---\")\n", "display(df_staff.tail(2))\n", "\n", "print(\"\\n--- Random Sample (2 rows) ---\")\n", "display(df_staff.sample(2, random_state=42))" ] }, { "cell_type": "code", "execution_count": 13, "id": "568d9744", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.594011Z", "iopub.status.busy": "2026-10-03T05:03:26.593920Z", "iopub.status.idle": "2026-10-03T05:03:26.600323Z", "shell.execute_reply": "2026-10-03T05:03:26.600064Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--- DataFrame Technical Diagnostics ---\n", "\n", "RangeIndex: 5 entries, 0 to 4\n", "Data columns (total 6 columns):\n", " # Column Non-Null Count Dtype\n", "--- ------ -------------- -----\n", " 0 Emp_ID 5 non-null int64\n", " 1 Name 5 non-null str \n", " 2 Department 5 non-null str \n", " 3 Salary 5 non-null int64\n", " 4 Years_Experience 5 non-null int64\n", " 5 Is_Remote 5 non-null bool \n", "dtypes: bool(1), int64(3), str(2)\n", "memory usage: 337.0 bytes\n" ] } ], "source": [ "# 2. Technical diagnostic with .info()\n", "print(\"--- DataFrame Technical Diagnostics ---\")\n", "df_staff.info()" ] }, { "cell_type": "code", "execution_count": 14, "id": "15291515", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.601435Z", "iopub.status.busy": "2026-10-03T05:03:26.601346Z", "iopub.status.idle": "2026-10-03T05:03:26.615740Z", "shell.execute_reply": "2026-10-03T05:03:26.615460Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--- Numerical Columns Statistical Summary ---\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Emp_IDSalaryYears_Experience
count5.0000005.0000005.000000
mean103.00000084000.0000007.000000
std1.58113917392.5271313.674235
min101.00000062000.0000003.000000
25%102.00000071000.0000004.000000
50%103.00000088000.0000007.000000
75%104.00000094000.0000009.000000
max105.000000105000.00000012.000000
\n", "
" ], "text/plain": [ " Emp_ID Salary Years_Experience\n", "count 5.000000 5.000000 5.000000\n", "mean 103.000000 84000.000000 7.000000\n", "std 1.581139 17392.527131 3.674235\n", "min 101.000000 62000.000000 3.000000\n", "25% 102.000000 71000.000000 4.000000\n", "50% 103.000000 88000.000000 7.000000\n", "75% 104.000000 94000.000000 9.000000\n", "max 105.000000 105000.000000 12.000000" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "--- All Columns Summary (including text/categorical) ---\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", " \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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
count5.000000555.0000005.0000005
uniqueNaN54NaNNaN2
topNaNAlice SmithITNaNNaNTrue
freqNaN12NaNNaN3
mean103.000000NaNNaN84000.0000007.000000NaN
std1.581139NaNNaN17392.5271313.674235NaN
min101.000000NaNNaN62000.0000003.000000NaN
25%102.000000NaNNaN71000.0000004.000000NaN
50%103.000000NaNNaN88000.0000007.000000NaN
75%104.000000NaNNaN94000.0000009.000000NaN
max105.000000NaNNaN105000.00000012.000000NaN
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience \\\n", "count 5.000000 5 5 5.000000 5.000000 \n", "unique NaN 5 4 NaN NaN \n", "top NaN Alice Smith IT NaN NaN \n", "freq NaN 1 2 NaN NaN \n", "mean 103.000000 NaN NaN 84000.000000 7.000000 \n", "std 1.581139 NaN NaN 17392.527131 3.674235 \n", "min 101.000000 NaN NaN 62000.000000 3.000000 \n", "25% 102.000000 NaN NaN 71000.000000 4.000000 \n", "50% 103.000000 NaN NaN 88000.000000 7.000000 \n", "75% 104.000000 NaN NaN 94000.000000 9.000000 \n", "max 105.000000 NaN NaN 105000.000000 12.000000 \n", "\n", " Is_Remote \n", "count 5 \n", "unique 2 \n", "top True \n", "freq 3 \n", "mean NaN \n", "std NaN \n", "min NaN \n", "25% NaN \n", "50% NaN \n", "75% NaN \n", "max NaN " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# 3. Statistical summary with .describe()\n", "print(\"--- Numerical Columns Statistical Summary ---\")\n", "display(df_staff.describe())\n", "\n", "# Include non-numeric / categorical columns too\n", "print(\"\\n--- All Columns Summary (including text/categorical) ---\")\n", "display(df_staff.describe(include='all'))" ] }, { "cell_type": "markdown", "id": "e76bead4", "metadata": {}, "source": [ "> 💡 **Pro-Tip:**\n", "> When working with large datasets, run `df.info(memory_usage='deep')` to measure the **true** memory consumption including dynamic Python string allocations!\n", ">\n", "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "f38f377a", "metadata": {}, "source": [ "\n", "---\n", "# Part II: Slicing, Indexing & Filtering\n", "\n", "## 4. Selection & Slicing: `loc` vs `iloc`\n", "\n", "Selecting specific rows and columns is the most frequent operation in data analysis. Beginners often struggle with when to use `[]`, `.loc[]`, or `.iloc[]`.\n", "\n", "Here is the unambiguous, foolproof rule:\n", "\n", "```\n", "+-----------------------------------------------------------------------------------------------+\n", "| SELECTION CHEAT SHEET & MENTAL MODEL |\n", "+-----------------------------------------------------------------------------------------------+\n", "| Method | Based On... | What to Pass | Endpoint Inclusion? |\n", "+----------+----------------------+--------------------------------+----------------------------+\n", "| df['C'] | Column Label | Column name or list of names | N/A (Columns only) |\n", "| .iloc | Integer Position | 0-based indices [row, col] | EXCLUSIVE stop (0:3 -> 0,1,2)|\n", "| .loc | Label Names | Row & column names [row, col] | INCLUSIVE stop ('A':'C') |\n", "| .iat | Integer Position | Scalar position [row, col] | N/A (Fast single cell) |\n", "| .at | Label Name | Scalar label [row, col] | N/A (Fast single cell) |\n", "+-----------------------------------------------------------------------------------------------+\n", "```\n", "\n", "### 4.1 Column Selection: Series vs DataFrame\n", "- **Single Bracket `df['Name']`**: Returns a 1D **`Series`**.\n", "- **Double Bracket `df[['Name', 'Salary']]`**: Returns a 2D **`DataFrame`** (even if you only request one column like `df[['Name']]`)." ] }, { "cell_type": "code", "execution_count": 15, "id": "05e09c19", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.616913Z", "iopub.status.busy": "2026-10-03T05:03:26.616819Z", "iopub.status.idle": "2026-10-03T05:03:26.621363Z", "shell.execute_reply": "2026-10-03T05:03:26.621095Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Type of df_staff['Name']: \n", "0 Alice Smith\n", "1 Bob Jones\n", "Name: Name, dtype: str\n", "\n", "Type of df_staff[['Name', 'Salary']]: \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", "
NameDepartmentSalary
0Alice SmithHR62000
1Bob JonesIT88000
2Charlie BrownMarketing71000
\n", "
" ], "text/plain": [ " Name Department Salary\n", "0 Alice Smith HR 62000\n", "1 Bob Jones IT 88000\n", "2 Charlie Brown Marketing 71000" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Single bracket returns a Series\n", "name_series = df_staff['Name']\n", "print(f\"Type of df_staff['Name']: {type(name_series)}\")\n", "print(name_series.head(2))\n", "\n", "# Double bracket returns a DataFrame\n", "sub_df = df_staff[['Name', 'Department', 'Salary']]\n", "print(f\"\\nType of df_staff[['Name', 'Salary']]: {type(sub_df)}\")\n", "display(sub_df.head(3))" ] }, { "cell_type": "markdown", "id": "da8db854", "metadata": {}, "source": [ "### 4.2 Positional Selection with `.iloc` (Integer-Location)\n", "`.iloc` works strictly with zero-based integer indices: `.iloc[row_selection, column_selection]`.\n", "It strictly follows standard Python slicing semantics: **the stop endpoint is excluded**!" ] }, { "cell_type": "code", "execution_count": 16, "id": "bb5d31c5", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.622499Z", "iopub.status.busy": "2026-10-03T05:03:26.622402Z", "iopub.status.idle": "2026-10-03T05:03:26.629455Z", "shell.execute_reply": "2026-10-03T05:03:26.629222Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Row at index position 0 (First Employee):\n", "Emp_ID 101\n", "Name Alice Smith\n", "Department HR\n", "Salary 62000\n", "Years_Experience 3\n", "Is_Remote True\n", "Name: 0, dtype: object\n", "\n", "Rows 0:3 and Columns 1:4:\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", "
NameDepartmentSalary
0Alice SmithHR62000
1Bob JonesIT88000
2Charlie BrownMarketing71000
\n", "
" ], "text/plain": [ " Name Department Salary\n", "0 Alice Smith HR 62000\n", "1 Bob Jones IT 88000\n", "2 Charlie Brown Marketing 71000" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Rows [0, 2, 4] and Columns [1, 3]:\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", "
NameSalary
0Alice Smith62000
2Charlie Brown71000
4Evan Wright105000
\n", "
" ], "text/plain": [ " Name Salary\n", "0 Alice Smith 62000\n", "2 Charlie Brown 71000\n", "4 Evan Wright 105000" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Last 2 rows, last 3 columns:\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", "
SalaryYears_ExperienceIs_Remote
3940009False
410500012True
\n", "
" ], "text/plain": [ " Salary Years_Experience Is_Remote\n", "3 94000 9 False\n", "4 105000 12 True" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# 1. Single row by integer position (returns Series)\n", "print(\"Row at index position 0 (First Employee):\")\n", "print(df_staff.iloc[0])\n", "\n", "# 2. Slice rows 0 to 3 (exclusive -> rows 0, 1, 2) and columns 1 to 4\n", "print(\"\\nRows 0:3 and Columns 1:4:\")\n", "display(df_staff.iloc[0:3, 1:4])\n", "\n", "# 3. Discontinuous selection using integer lists\n", "print(\"\\nRows [0, 2, 4] and Columns [1, 3]:\")\n", "display(df_staff.iloc[[0, 2, 4], [1, 3]])\n", "\n", "# 4. Negative integer indexing (Last 2 rows, last 3 columns)\n", "print(\"\\nLast 2 rows, last 3 columns:\")\n", "display(df_staff.iloc[-2:, -3:])" ] }, { "cell_type": "markdown", "id": "9269cfe2", "metadata": {}, "source": [ "### 4.3 Label-Based Selection with `.loc` (Label-Location)\n", "`.loc` selects data by the **actual names** of the rows and columns: `.loc[row_label, column_label]`.\n", "**Crucial Rule:** Unlike standard Python slicing, when slicing with `.loc`, **the stop label is INCLUDED**!" ] }, { "cell_type": "code", "execution_count": 17, "id": "86f1a2d5", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.630573Z", "iopub.status.busy": "2026-10-03T05:03:26.630479Z", "iopub.status.idle": "2026-10-03T05:03:26.637766Z", "shell.execute_reply": "2026-10-03T05:03:26.637519Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DataFrame indexed by Employee Name:\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Emp_IDDepartmentSalaryYears_ExperienceIs_Remote
Name
Alice Smith101HR620003True
Bob Jones102IT880007True
Charlie Brown103Marketing710004False
Diana Prince104IT940009False
Evan Wright105Finance10500012True
\n", "
" ], "text/plain": [ " Emp_ID Department Salary Years_Experience Is_Remote\n", "Name \n", "Alice Smith 101 HR 62000 3 True\n", "Bob Jones 102 IT 88000 7 True\n", "Charlie Brown 103 Marketing 71000 4 False\n", "Diana Prince 104 IT 94000 9 False\n", "Evan Wright 105 Finance 105000 12 True" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Charlie Brown's Record:\n", "Emp_ID 103\n", "Department Marketing\n", "Salary 71000\n", "Years_Experience 4\n", "Is_Remote False\n", "Name: Charlie Brown, dtype: object\n", "\n", "Diana Prince's Salary: $94,000\n", "\n", "Slice from 'Bob Jones' to 'Diana Prince':\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", "
DepartmentSalaryYears_Experience
Name
Bob JonesIT880007
Charlie BrownMarketing710004
Diana PrinceIT940009
\n", "
" ], "text/plain": [ " Department Salary Years_Experience\n", "Name \n", "Bob Jones IT 88000 7\n", "Charlie Brown Marketing 71000 4\n", "Diana Prince IT 94000 9" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Set employee name as the DataFrame index to showcase .loc\n", "df_named = df_staff.set_index('Name')\n", "print(\"DataFrame indexed by Employee Name:\")\n", "display(df_named)\n", "\n", "# 1. Select a single row by label\n", "print(\"\\nCharlie Brown's Record:\")\n", "print(df_named.loc['Charlie Brown'])\n", "\n", "# 2. Select specific row and specific columns\n", "print(f\"\\nDiana Prince's Salary: ${df_named.loc['Diana Prince', 'Salary']:,}\")\n", "\n", "# 3. Slice from 'Bob Jones' to 'Diana Prince' (Diana IS included!)\n", "print(\"\\nSlice from 'Bob Jones' to 'Diana Prince':\")\n", "display(df_named.loc['Bob Jones':'Diana Prince', ['Department', 'Salary', 'Years_Experience']])" ] }, { "cell_type": "markdown", "id": "55d7d69e", "metadata": {}, "source": [ "### 4.4 Ultra-Fast Scalar Lookups with `.at` and `.iat`\n", "When you need to read or update a single cell inside a high-throughput loop, `.loc` and `.iloc` incur extra overhead for series validation.\n", "- **`.at[row_label, col_label]`**: Fast scalar access by label.\n", "- **`.iat[row_idx, col_idx]`**: Fast scalar access by integer position." ] }, { "cell_type": "code", "execution_count": 18, "id": "c7eeddff", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.638923Z", "iopub.status.busy": "2026-10-03T05:03:26.638834Z", "iopub.status.idle": "2026-10-03T05:03:26.640983Z", "shell.execute_reply": "2026-10-03T05:03:26.640717Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Scalar lookup via .at: $62,000\n", "Scalar lookup via .iat: $62,000\n" ] } ], "source": [ "# Fast scalar lookup\n", "val_at = df_named.at['Alice Smith', 'Salary']\n", "val_iat = df_staff.iat[0, 3] # Row 0, Col 3 ('Salary')\n", "\n", "print(f\"Scalar lookup via .at: ${val_at:,}\")\n", "print(f\"Scalar lookup via .iat: ${val_iat:,}\")" ] }, { "cell_type": "markdown", "id": "5cc1176a", "metadata": {}, "source": [ "> ⚠️ **Common Trap:**\n", "> Slicing with `.iloc[0:2]` returns 2 rows (indices 0 and 1).\n", "> Slicing with `.loc[0:2]` on a default integer index returns 3 rows (indices 0, 1, and 2)!\n", "> Always remember: `.loc` includes both boundaries!\n", ">\n", "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "3939afae", "metadata": {}, "source": [ "\n", "---\n", "## 5. Filtering & Boolean Queries\n", "\n", "Filtering extracts records that satisfy business criteria (e.g. \"Find all remote employees in IT earning over $80,000\").\n", "\n", "### 5.1 How Boolean Indexing Works Under the Hood\n", "1. When you write `df_staff['Salary'] > 75000`, Pandas applies the comparison operator element-wise to every row.\n", "2. This generates a **Boolean Mask** (a Series of `True` and `False` values).\n", "3. When you pass this mask back into `df_staff[mask]`, Pandas retains only rows where the mask evaluates to `True`." ] }, { "cell_type": "code", "execution_count": 19, "id": "a7f9aa7f", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.642081Z", "iopub.status.busy": "2026-10-03T05:03:26.641998Z", "iopub.status.idle": "2026-10-03T05:03:26.645848Z", "shell.execute_reply": "2026-10-03T05:03:26.645530Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Boolean Mask:\n", "0 False\n", "1 True\n", "2 False\n", "3 True\n", "4 True\n", "Name: Salary, dtype: bool\n", "\n", "Employees earning > $75k:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
1102Bob JonesIT880007True
3104Diana PrinceIT940009False
4105Evan WrightFinance10500012True
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "1 102 Bob Jones IT 88000 7 True\n", "3 104 Diana Prince IT 94000 9 False\n", "4 105 Evan Wright Finance 105000 12 True" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# 1. Generate the boolean mask\n", "mask_high_salary = df_staff['Salary'] > 75000\n", "print(\"Boolean Mask:\")\n", "print(mask_high_salary)\n", "\n", "# 2. Apply mask to filter DataFrame\n", "print(\"\\nEmployees earning > $75k:\")\n", "display(df_staff[mask_high_salary])" ] }, { "cell_type": "markdown", "id": "eaeea55c", "metadata": {}, "source": [ "### 5.2 Combining Multiple Conditions: The 3 Rules\n", "When combining conditions in Pandas, standard Python keywords `and`, `or`, and `not` will **raise a `ValueError`**!\n", "Instead, you must use bitwise operators:\n", "- **`&`** for AND (both conditions must be true)\n", "- **`|`** for OR (at least one condition must be true)\n", "- **`~`** for NOT (negates the condition)\n", "\n", "**The Golden Rule:** Every individual condition MUST be wrapped in parentheses `()`!\n", "This is required because Python's bitwise operator precedence is higher than comparison operators (`>`, `==`, `<`). Without parentheses, `df['A'] > 5 & df['B'] < 10` is evaluated as `5 & df['B']`, causing a syntax crash." ] }, { "cell_type": "code", "execution_count": 20, "id": "9fcdb6d6", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.646962Z", "iopub.status.busy": "2026-10-03T05:03:26.646870Z", "iopub.status.idle": "2026-10-03T05:03:26.654980Z", "shell.execute_reply": "2026-10-03T05:03:26.654740Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "IT Employees earning > $90k:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
3104Diana PrinceIT940009False
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "3 104 Diana Prince IT 94000 9 False" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Senior (>=10 yrs) OR Remote Employees:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
0101Alice SmithHR620003True
1102Bob JonesIT880007True
4105Evan WrightFinance10500012True
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "0 101 Alice Smith HR 62000 3 True\n", "1 102 Bob Jones IT 88000 7 True\n", "4 105 Evan Wright Finance 105000 12 True" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Non-IT Employees:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
0101Alice SmithHR620003True
2103Charlie BrownMarketing710004False
4105Evan WrightFinance10500012True
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "0 101 Alice Smith HR 62000 3 True\n", "2 103 Charlie Brown Marketing 71000 4 False\n", "4 105 Evan Wright Finance 105000 12 True" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# 1. AND Condition: Department == 'IT' AND Salary > 90,000\n", "it_high_earners = df_staff[(df_staff['Department'] == 'IT') & (df_staff['Salary'] > 90000)]\n", "print(\"IT Employees earning > $90k:\")\n", "display(it_high_earners)\n", "\n", "# 2. OR Condition: Years_Experience >= 10 OR Is_Remote == True\n", "senior_or_remote = df_staff[(df_staff['Years_Experience'] >= 10) | (df_staff['Is_Remote'] == True)]\n", "print(\"\\nSenior (>=10 yrs) OR Remote Employees:\")\n", "display(senior_or_remote)\n", "\n", "# 3. NOT Condition: NOT in IT\n", "non_it_staff = df_staff[~(df_staff['Department'] == 'IT')]\n", "print(\"\\nNon-IT Employees:\")\n", "display(non_it_staff)" ] }, { "cell_type": "markdown", "id": "4f82ed06", "metadata": {}, "source": [ "### 5.3 Convenient Helper Filtering Methods\n", "\n", "#### Method 1: `.isin()` for Multiple Category Matches\n", "Instead of chaining endless `|` conditions (`(df['Dept'] == 'HR') | (df['Dept'] == 'IT') | ...`), pass a list to `.isin()`:" ] }, { "cell_type": "code", "execution_count": 21, "id": "fc94ba65", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.656159Z", "iopub.status.busy": "2026-10-03T05:03:26.656066Z", "iopub.status.idle": "2026-10-03T05:03:26.659913Z", "shell.execute_reply": "2026-10-03T05:03:26.659673Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Employees in HR or Finance:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
0101Alice SmithHR620003True
4105Evan WrightFinance10500012True
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "0 101 Alice Smith HR 62000 3 True\n", "4 105 Evan Wright Finance 105000 12 True" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "target_depts = ['HR', 'Finance']\n", "selected_staff = df_staff[df_staff['Department'].isin(target_depts)]\n", "print(\"Employees in HR or Finance:\")\n", "display(selected_staff)" ] }, { "cell_type": "markdown", "id": "7e79e212", "metadata": {}, "source": [ "#### Method 2: `.between(left, right)` for Range Checks\n", "Replaces `(df['Salary'] >= 70000) & (df['Salary'] <= 90000)`. Both boundaries are inclusive by default:" ] }, { "cell_type": "code", "execution_count": 22, "id": "30630b44", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.661033Z", "iopub.status.busy": "2026-10-03T05:03:26.660937Z", "iopub.status.idle": "2026-10-03T05:03:26.664333Z", "shell.execute_reply": "2026-10-03T05:03:26.664075Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Employees with Salary between $70k and $90k:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
1102Bob JonesIT880007True
2103Charlie BrownMarketing710004False
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "1 102 Bob Jones IT 88000 7 True\n", "2 103 Charlie Brown Marketing 71000 4 False" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "mid_salary_staff = df_staff[df_staff['Salary'].between(70000, 90000)]\n", "print(\"Employees with Salary between $70k and $90k:\")\n", "display(mid_salary_staff)" ] }, { "cell_type": "markdown", "id": "1d98bf76", "metadata": {}, "source": [ "### 5.4 SQL-Style Querying with `.query()`\n", "Pandas provides `.query()`, allowing you to write filtering conditions as clean, legible strings.\n", "To reference external Python variables inside `.query()`, prefix the variable name with `@`:" ] }, { "cell_type": "code", "execution_count": 23, "id": "d653aebc", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.665427Z", "iopub.status.busy": "2026-10-03T05:03:26.665339Z", "iopub.status.idle": "2026-10-03T05:03:26.670039Z", "shell.execute_reply": "2026-10-03T05:03:26.669770Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Employees in IT with >= 5 years experience (via .query):\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_Remote
1102Bob JonesIT880007True
3104Diana PrinceIT940009False
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote\n", "1 102 Bob Jones IT 88000 7 True\n", "3 104 Diana Prince IT 94000 9 False" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "min_experience = 5\n", "dept_target = 'IT'\n", "\n", "# Using .query() with @variable reference\n", "query_results = df_staff.query(\"Department == @dept_target and Years_Experience >= @min_experience\")\n", "print(f\"Employees in {dept_target} with >= {min_experience} years experience (via .query):\")\n", "display(query_results)" ] }, { "cell_type": "markdown", "id": "3717124f", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "606fe02c", "metadata": {}, "source": [ "\n", "---\n", "# Part III: Data Modification & Cleaning\n", "\n", "## 6. Modifying Data: Adding, Renaming & Dropping\n", "\n", "### 6.1 Adding New Columns (Vectorized Arithmetic)\n", "Adding calculated features in Pandas is simple: assign the result of a vectorized computation directly to `df['New_Column']`.\n", "Because operations are vectorized, calculations execute in optimized C code across millions of rows simultaneously without any Python `for` loops." ] }, { "cell_type": "code", "execution_count": 24, "id": "5fa3e017", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.671151Z", "iopub.status.busy": "2026-10-03T05:03:26.671067Z", "iopub.status.idle": "2026-10-03T05:03:26.676827Z", "shell.execute_reply": "2026-10-03T05:03:26.676570Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DataFrame after adding calculated columns:\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NameSalaryBonusTotal_CompensationMonthly_GrossSenior_Level
0Alice Smith620007440.069440.05166.67False
1Bob Jones8800010560.098560.07333.33False
2Charlie Brown710008520.079520.05916.67False
3Diana Prince9400011280.0105280.07833.33True
4Evan Wright10500012600.0117600.08750.00True
\n", "
" ], "text/plain": [ " Name Salary Bonus Total_Compensation Monthly_Gross \\\n", "0 Alice Smith 62000 7440.0 69440.0 5166.67 \n", "1 Bob Jones 88000 10560.0 98560.0 7333.33 \n", "2 Charlie Brown 71000 8520.0 79520.0 5916.67 \n", "3 Diana Prince 94000 11280.0 105280.0 7833.33 \n", "4 Evan Wright 105000 12600.0 117600.0 8750.00 \n", "\n", " Senior_Level \n", "0 False \n", "1 False \n", "2 False \n", "3 True \n", "4 True " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Work on a fresh copy\n", "df_work = df_staff.copy()\n", "\n", "# 1. Simple arithmetic: Annual bonus is 12% of salary\n", "df_work['Bonus'] = df_work['Salary'] * 0.12\n", "\n", "# 2. Multi-column calculation: Total compensation\n", "df_work['Total_Compensation'] = df_work['Salary'] + df_work['Bonus']\n", "\n", "# 3. Calculated boolean flag\n", "df_work['Senior_Level'] = df_work['Years_Experience'] >= 8\n", "\n", "# 4. Using .assign() for method chaining\n", "df_work = df_work.assign(\n", " Monthly_Gross=lambda d: (d['Salary'] / 12).round(2)\n", ")\n", "\n", "print(\"DataFrame after adding calculated columns:\")\n", "display(df_work[['Name', 'Salary', 'Bonus', 'Total_Compensation', 'Monthly_Gross', 'Senior_Level']])" ] }, { "cell_type": "markdown", "id": "babd6805", "metadata": {}, "source": [ "### 6.2 Renaming Columns & Indices\n", "Use `.rename()` with a dictionary mapping `{'old_name': 'new_name'}`:" ] }, { "cell_type": "code", "execution_count": 66, "id": "e491b1d1", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.677959Z", "iopub.status.busy": "2026-10-03T05:03:26.677869Z", "iopub.status.idle": "2026-10-03T05:03:26.679854Z", "shell.execute_reply": "2026-10-03T05:03:26.679548Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Renamed Columns:\n", "['Employee_Identifier', 'Name', 'Department', 'Salary', 'Years_Experience', 'Remote_Worker', 'Bonus', 'Total_Compensation', 'Senior_Level', 'Monthly_Gross']\n" ] } ], "source": [ "df_renamed = df_work.rename(columns={\n", " 'Emp_ID': 'Employee_Identifier',\n", " 'Is_Remote': 'Remote_Worker'\n", "})\n", "print(\"Renamed Columns:\")\n", "print(list(df_renamed.columns))" ] }, { "cell_type": "markdown", "id": "dc769f71", "metadata": {}, "source": [ "### 6.3 Dropping Columns and Rows\n", "Use `.drop()`:\n", "- Specify `columns=['Col1', 'Col2']` to drop columns.\n", "- Specify `index=[0, 1]` to drop rows by index label.\n", "- **The Axis Model:** In Pandas, `axis=0` refers to rows (vertical axis), and `axis=1` refers to columns (horizontal axis)." ] }, { "cell_type": "code", "execution_count": 26, "id": "1a92c2eb", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.680959Z", "iopub.status.busy": "2026-10-03T05:03:26.680870Z", "iopub.status.idle": "2026-10-03T05:03:26.687850Z", "shell.execute_reply": "2026-10-03T05:03:26.687598Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "After dropping Bonus and Monthly_Gross:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_RemoteTotal_CompensationSenior_Level
0101Alice SmithHR620003True69440.0False
1102Bob JonesIT880007True98560.0False
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote \\\n", "0 101 Alice Smith HR 62000 3 True \n", "1 102 Bob Jones IT 88000 7 True \n", "\n", " Total_Compensation Senior_Level \n", "0 69440.0 False \n", "1 98560.0 False " ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "After dropping row indices 0 and 2:\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", "
Emp_IDNameDepartmentSalaryYears_ExperienceIs_RemoteBonusTotal_CompensationSenior_LevelMonthly_Gross
1102Bob JonesIT880007True10560.098560.0False7333.33
3104Diana PrinceIT940009False11280.0105280.0True7833.33
\n", "
" ], "text/plain": [ " Emp_ID Name Department Salary Years_Experience Is_Remote \\\n", "1 102 Bob Jones IT 88000 7 True \n", "3 104 Diana Prince IT 94000 9 False \n", "\n", " Bonus Total_Compensation Senior_Level Monthly_Gross \n", "1 10560.0 98560.0 False 7333.33 \n", "3 11280.0 105280.0 True 7833.33 " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Dropping columns\n", "df_dropped_cols = df_work.drop(columns=['Bonus', 'Monthly_Gross'])\n", "print(\"After dropping Bonus and Monthly_Gross:\")\n", "display(df_dropped_cols.head(2))\n", "\n", "# Dropping rows by index label\n", "df_dropped_rows = df_work.drop(index=[0, 2])\n", "print(\"\\nAfter dropping row indices 0 and 2:\")\n", "display(df_dropped_rows.head(2))" ] }, { "cell_type": "markdown", "id": "4397d53c", "metadata": {}, "source": [ "> 💡 **Best Practice Note on `inplace=True`:**\n", "> You may encounter `df.drop(..., inplace=True)` in older tutorials. In modern Pandas, **`inplace=True` is officially discouraged and slated for future deprecation**.\n", "> Why?\n", "> 1. It rarely provides true memory savings (it usually makes a copy internally anyway).\n", "> 2. It breaks method chaining (`df.drop(...).rename(...)`).\n", "> 3. Direct assignment (`df = df.drop(...)`) makes data flow clear and bug-free!\n", ">\n", "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "700edce6", "metadata": {}, "source": [ "\n", "---\n", "## 7. Handling Missing Data (NaNs)\n", "\n", "Missing values are an unavoidable reality of real-world datasets: survey respondents skip questions, sensors disconnect, and database joins produce unmatched records.\n", "\n", "In Pandas:\n", "- Floating-point missing values are represented by **`np.nan`** (IEEE 754 floating-point Not-a-Number).\n", "- Modern Pandas also supports **`pd.NA`** as an experimental unified missing value indicator across all types.\n", "\n", "### 7.1 The Peculiar Nature of `np.nan`\n", "In standard computer science, `NaN` is not equal to anything — **not even itself**!\n", "This means you can NEVER check for missing data using `if x == np.nan:`. You MUST use `pd.isna()`!" ] }, { "cell_type": "code", "execution_count": 27, "id": "92cd03f5", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.688989Z", "iopub.status.busy": "2026-10-03T05:03:26.688897Z", "iopub.status.idle": "2026-10-03T05:03:26.690772Z", "shell.execute_reply": "2026-10-03T05:03:26.690534Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Is np.nan == np.nan? False\n", "Is pd.isna(np.nan)? True\n" ] } ], "source": [ "print(\"Is np.nan == np.nan?\", np.nan == np.nan) # Returns False!\n", "print(\"Is pd.isna(np.nan)? \", pd.isna(np.nan)) # Returns True!" ] }, { "cell_type": "markdown", "id": "2edd3fb9", "metadata": {}, "source": [ "Let's build a realistic customer dataset containing various missing fields:" ] }, { "cell_type": "code", "execution_count": 28, "id": "38cc4679", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.691830Z", "iopub.status.busy": "2026-10-03T05:03:26.691745Z", "iopub.status.idle": "2026-10-03T05:03:26.696612Z", "shell.execute_reply": "2026-10-03T05:03:26.696361Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Raw Customer Dataset with Missing Values:\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Customer_IDNameOrders_CountAnnual_SpendSatisfaction_ScoreRegion
01001Acme Corp14.014000.04.5North
11002GlobexNaN45000.03.8East
21003Soylent Corp8.0NaN4.2NaN
31004Initech25.032000.0NaNWest
41005Umbrella CorpNaNNaNNaNEast
51006Hooli31.068000.04.9North
\n", "
" ], "text/plain": [ " Customer_ID Name Orders_Count Annual_Spend Satisfaction_Score \\\n", "0 1001 Acme Corp 14.0 14000.0 4.5 \n", "1 1002 Globex NaN 45000.0 3.8 \n", "2 1003 Soylent Corp 8.0 NaN 4.2 \n", "3 1004 Initech 25.0 32000.0 NaN \n", "4 1005 Umbrella Corp NaN NaN NaN \n", "5 1006 Hooli 31.0 68000.0 4.9 \n", "\n", " Region \n", "0 North \n", "1 East \n", "2 NaN \n", "3 West \n", "4 East \n", "5 North " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "customer_data = {\n", " 'Customer_ID': [1001, 1002, 1003, 1004, 1005, 1006],\n", " 'Name': ['Acme Corp', 'Globex', 'Soylent Corp', 'Initech', 'Umbrella Corp', 'Hooli'],\n", " 'Orders_Count': [14, np.nan, 8, 25, np.nan, 31],\n", " 'Annual_Spend': [14000.0, 45000.0, np.nan, 32000.0, np.nan, 68000.0],\n", " 'Satisfaction_Score': [4.5, 3.8, 4.2, np.nan, np.nan, 4.9],\n", " 'Region': ['North', 'East', np.nan, 'West', 'East', 'North']\n", "}\n", "\n", "df_cust = pd.DataFrame(customer_data)\n", "print(\"Raw Customer Dataset with Missing Values:\")\n", "display(df_cust)" ] }, { "cell_type": "markdown", "id": "823edd11", "metadata": {}, "source": [ "### 7.2 Detecting & Quantifying Missing Data\n", "Use `.isna()` to flag missing values, and `.sum()` to count them per column:" ] }, { "cell_type": "code", "execution_count": 29, "id": "5a23e54f", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.697689Z", "iopub.status.busy": "2026-10-03T05:03:26.697604Z", "iopub.status.idle": "2026-10-03T05:03:26.700896Z", "shell.execute_reply": "2026-10-03T05:03:26.700658Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Missing values per column:\n", "Customer_ID 0\n", "Name 0\n", "Orders_Count 2\n", "Annual_Spend 2\n", "Satisfaction_Score 2\n", "Region 1\n", "dtype: int64\n", "\n", "Percentage of missing data per column:\n", "Customer_ID 0.0%\n", "Name 0.0%\n", "Orders_Count 33.3%\n", "Annual_Spend 33.3%\n", "Satisfaction_Score 33.3%\n", "Region 16.7%\n", "dtype: str\n", "\n", "Total missing cells in table: 7\n" ] } ], "source": [ "# 1. Total missing values per column\n", "print(\"Missing values per column:\")\n", "print(df_cust.isna().sum())\n", "\n", "# 2. Percentage of missing data per column\n", "print(\"\\nPercentage of missing data per column:\")\n", "print((df_cust.isna().mean() * 100).round(1).astype(str) + '%')\n", "\n", "# 3. Overall total missing values across entire table\n", "print(f\"\\nTotal missing cells in table: {df_cust.isna().sum().sum()}\")" ] }, { "cell_type": "markdown", "id": "12b73622", "metadata": {}, "source": [ "### 7.3 Dropping Missing Values with `.dropna()`\n", "Dropping rows is appropriate when only a tiny fraction of data is missing, or when critical identifier columns are empty.\n", "Key parameters:\n", "- `axis=0` (default): Drop rows containing missing values.\n", "- `how='any'` (default): Drop row if AT LEAST ONE column has NaN.\n", "- `how='all'`: Drop row only if ALL columns are NaN.\n", "- `subset=['ColA', 'ColB']`: Only consider NaNs in these specified columns." ] }, { "cell_type": "code", "execution_count": 30, "id": "a8396ca1", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.702095Z", "iopub.status.busy": "2026-10-03T05:03:26.702007Z", "iopub.status.idle": "2026-10-03T05:03:26.708971Z", "shell.execute_reply": "2026-10-03T05:03:26.708738Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--- Drop ANY Missing Value ---\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", "
Customer_IDNameOrders_CountAnnual_SpendSatisfaction_ScoreRegion
01001Acme Corp14.014000.04.5North
51006Hooli31.068000.04.9North
\n", "
" ], "text/plain": [ " Customer_ID Name Orders_Count Annual_Spend Satisfaction_Score \\\n", "0 1001 Acme Corp 14.0 14000.0 4.5 \n", "5 1006 Hooli 31.0 68000.0 4.9 \n", "\n", " Region \n", "0 North \n", "5 North " ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "--- Drop Only If Annual_Spend is Missing ---\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", " \n", " \n", " \n", " \n", " \n", "
Customer_IDNameOrders_CountAnnual_SpendSatisfaction_ScoreRegion
01001Acme Corp14.014000.04.5North
11002GlobexNaN45000.03.8East
31004Initech25.032000.0NaNWest
51006Hooli31.068000.04.9North
\n", "
" ], "text/plain": [ " Customer_ID Name Orders_Count Annual_Spend Satisfaction_Score \\\n", "0 1001 Acme Corp 14.0 14000.0 4.5 \n", "1 1002 Globex NaN 45000.0 3.8 \n", "3 1004 Initech 25.0 32000.0 NaN \n", "5 1006 Hooli 31.0 68000.0 4.9 \n", "\n", " Region \n", "0 North \n", "1 East \n", "3 West \n", "5 North " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Drop rows where ANY column is missing\n", "print(\"--- Drop ANY Missing Value ---\")\n", "display(df_cust.dropna())\n", "\n", "# Drop rows where 'Annual_Spend' specifically is missing\n", "print(\"\\n--- Drop Only If Annual_Spend is Missing ---\")\n", "display(df_cust.dropna(subset=['Annual_Spend']))" ] }, { "cell_type": "markdown", "id": "bb9ad854", "metadata": {}, "source": [ "### 7.4 Imputing Missing Values with `.fillna()`\n", "Throwing away data can bias analysis or destroy valuable sample size. **Imputation** replaces missing values with informed approximations:\n", "- **Numerical columns:** Replace with column `mean()` (symmetric data) or `median()` (skewed data with outliers).\n", "- **Categorical columns:** Replace with `'Unknown'` or the `mode()` (most frequent category).\n", "- **Time-series data:** Forward fill with `.ffill()` (carry previous known value forward) or backward fill with `.bfill()`." ] }, { "cell_type": "code", "execution_count": 31, "id": "703812b3", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.710052Z", "iopub.status.busy": "2026-10-03T05:03:26.709962Z", "iopub.status.idle": "2026-10-03T05:03:26.715597Z", "shell.execute_reply": "2026-10-03T05:03:26.715345Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Imputed spend with median: $38,500.00\n", "Imputed satisfaction with mean: 4.35\n", "\n", "Fully Imputed Clean DataFrame:\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Customer_IDNameOrders_CountAnnual_SpendSatisfaction_ScoreRegion
01001Acme Corp14.014000.04.50North
11002Globex0.045000.03.80East
21003Soylent Corp8.038500.04.20Unknown
31004Initech25.032000.04.35West
41005Umbrella Corp0.038500.04.35East
51006Hooli31.068000.04.90North
\n", "
" ], "text/plain": [ " Customer_ID Name Orders_Count Annual_Spend Satisfaction_Score \\\n", "0 1001 Acme Corp 14.0 14000.0 4.50 \n", "1 1002 Globex 0.0 45000.0 3.80 \n", "2 1003 Soylent Corp 8.0 38500.0 4.20 \n", "3 1004 Initech 25.0 32000.0 4.35 \n", "4 1005 Umbrella Corp 0.0 38500.0 4.35 \n", "5 1006 Hooli 31.0 68000.0 4.90 \n", "\n", " Region \n", "0 North \n", "1 East \n", "2 Unknown \n", "3 West \n", "4 East \n", "5 North " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "df_clean = df_cust.copy()\n", "\n", "# 1. Impute categorical column with constant\n", "df_clean['Region'] = df_clean['Region'].fillna('Unknown')\n", "\n", "# 2. Impute count with 0\n", "df_clean['Orders_Count'] = df_clean['Orders_Count'].fillna(0)\n", "\n", "# 3. Impute Annual_Spend with column median\n", "spend_median = df_clean['Annual_Spend'].median()\n", "df_clean['Annual_Spend'] = df_clean['Annual_Spend'].fillna(spend_median)\n", "\n", "# 4. Impute Satisfaction_Score with column mean\n", "satisfaction_mean = df_clean['Satisfaction_Score'].mean()\n", "df_clean['Satisfaction_Score'] = df_clean['Satisfaction_Score'].fillna(satisfaction_mean).round(2)\n", "\n", "print(f\"Imputed spend with median: ${spend_median:,.2f}\")\n", "print(f\"Imputed satisfaction with mean: {satisfaction_mean:.2f}\")\n", "print(\"\\nFully Imputed Clean DataFrame:\")\n", "display(df_clean)" ] }, { "cell_type": "markdown", "id": "528a6c91", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "83b02928", "metadata": {}, "source": [ "\n", "---\n", "## 8. Sorting, Ranking & Index Manipulation\n", "\n", "### 8.1 Sorting by Values\n", "Use `.sort_values(by=..., ascending=...)`:\n", "- Pass a single column name to sort by one attribute.\n", "- Pass a list of column names and a corresponding list of booleans to `ascending` to execute multi-level sorting (e.g. sort Department A–Z, then Salary High-to-Low within each department)." ] }, { "cell_type": "code", "execution_count": 32, "id": "ba860253", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.716740Z", "iopub.status.busy": "2026-10-03T05:03:26.716650Z", "iopub.status.idle": "2026-10-03T05:03:26.725605Z", "shell.execute_reply": "2026-10-03T05:03:26.725349Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Customers sorted by Annual Spend (Descending):\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", "
Customer_IDNameOrders_CountAnnual_SpendSatisfaction_ScoreRegion
51006Hooli31.068000.04.9North
11002Globex0.045000.03.8East
21003Soylent Corp8.038500.04.2Unknown
\n", "
" ], "text/plain": [ " Customer_ID Name Orders_Count Annual_Spend Satisfaction_Score \\\n", "5 1006 Hooli 31.0 68000.0 4.9 \n", "1 1002 Globex 0.0 45000.0 3.8 \n", "2 1003 Soylent Corp 8.0 38500.0 4.2 \n", "\n", " Region \n", "5 North \n", "1 East \n", "2 Unknown " ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Sorted by Region (A-Z), then Spend (High to Low):\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Customer_IDNameOrders_CountAnnual_SpendSatisfaction_ScoreRegion
11002Globex0.045000.03.80East
41005Umbrella Corp0.038500.04.35East
51006Hooli31.068000.04.90North
01001Acme Corp14.014000.04.50North
21003Soylent Corp8.038500.04.20Unknown
31004Initech25.032000.04.35West
\n", "
" ], "text/plain": [ " Customer_ID Name Orders_Count Annual_Spend Satisfaction_Score \\\n", "1 1002 Globex 0.0 45000.0 3.80 \n", "4 1005 Umbrella Corp 0.0 38500.0 4.35 \n", "5 1006 Hooli 31.0 68000.0 4.90 \n", "0 1001 Acme Corp 14.0 14000.0 4.50 \n", "2 1003 Soylent Corp 8.0 38500.0 4.20 \n", "3 1004 Initech 25.0 32000.0 4.35 \n", "\n", " Region \n", "1 East \n", "4 East \n", "5 North \n", "0 North \n", "2 Unknown \n", "3 West " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Single column sort (Highest spend first)\n", "sorted_spend = df_clean.sort_values(by='Annual_Spend', ascending=False)\n", "print(\"Customers sorted by Annual Spend (Descending):\")\n", "display(sorted_spend.head(3))\n", "\n", "# Multi-column sort: Region (Ascending), then Annual_Spend (Descending)\n", "multi_sort = df_clean.sort_values(\n", " by=['Region', 'Annual_Spend'],\n", " ascending=[True, False]\n", ")\n", "print(\"\\nSorted by Region (A-Z), then Spend (High to Low):\")\n", "display(multi_sort)" ] }, { "cell_type": "markdown", "id": "d9d54664", "metadata": {}, "source": [ "### 8.2 Ranking Values with `.rank()`\n", "Sorting reorders rows, whereas `.rank()` assigns numerical standings ($1, 2, 3, \\dots$) without changing row order:\n", "- `method='average'`: Default; assigns the average rank to ties.\n", "- `method='min'`: Competition ranking (e.g. Olympic medals: two silver medalists tied for 2nd means next place is 4th).\n", "- `method='dense'`: Like `min`, but does not leave gaps after ties (next place is 3rd)." ] }, { "cell_type": "code", "execution_count": 33, "id": "fb241a11", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.726750Z", "iopub.status.busy": "2026-10-03T05:03:26.726657Z", "iopub.status.idle": "2026-10-03T05:03:26.731762Z", "shell.execute_reply": "2026-10-03T05:03:26.731530Z" } }, "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", "
NameAnnual_SpendSpend_Rank
5Hooli68000.01
1Globex45000.02
2Soylent Corp38500.03
4Umbrella Corp38500.03
3Initech32000.05
0Acme Corp14000.06
\n", "
" ], "text/plain": [ " Name Annual_Spend Spend_Rank\n", "5 Hooli 68000.0 1\n", "1 Globex 45000.0 2\n", "2 Soylent Corp 38500.0 3\n", "4 Umbrella Corp 38500.0 3\n", "3 Initech 32000.0 5\n", "0 Acme Corp 14000.0 6" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "df_ranked = df_clean.copy()\n", "df_ranked['Spend_Rank'] = df_ranked['Annual_Spend'].rank(ascending=False, method='min').astype(int)\n", "display(df_ranked[['Name', 'Annual_Spend', 'Spend_Rank']].sort_values(by='Spend_Rank'))" ] }, { "cell_type": "markdown", "id": "c6760761", "metadata": {}, "source": [ "### 8.3 Resetting & Setting the Index\n", "After sorting or filtering, row index labels become scrambled (e.g. 5, 1, 3, 0).\n", "- **`.reset_index(drop=True)`**: Discards old scrambled labels and generates a clean sequence starting at 0.\n", "- **`.set_index('Column_Name')`**: Promotes an existing column into the row index." ] }, { "cell_type": "code", "execution_count": 34, "id": "23a32971", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.732841Z", "iopub.status.busy": "2026-10-03T05:03:26.732756Z", "iopub.status.idle": "2026-10-03T05:03:26.739539Z", "shell.execute_reply": "2026-10-03T05:03:26.739249Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index reset cleanly from 0 to N-1:\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", "
Customer_IDNameOrders_CountAnnual_SpendSatisfaction_ScoreRegion
01006Hooli31.068000.04.9North
11002Globex0.045000.03.8East
21003Soylent Corp8.038500.04.2Unknown
\n", "
" ], "text/plain": [ " Customer_ID Name Orders_Count Annual_Spend Satisfaction_Score \\\n", "0 1006 Hooli 31.0 68000.0 4.9 \n", "1 1002 Globex 0.0 45000.0 3.8 \n", "2 1003 Soylent Corp 8.0 38500.0 4.2 \n", "\n", " Region \n", "0 North \n", "1 East \n", "2 Unknown " ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "DataFrame indexed by Customer_ID:\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", "
NameOrders_CountAnnual_SpendSatisfaction_ScoreRegion
Customer_ID
1006Hooli31.068000.04.9North
1002Globex0.045000.03.8East
\n", "
" ], "text/plain": [ " Name Orders_Count Annual_Spend Satisfaction_Score Region\n", "Customer_ID \n", "1006 Hooli 31.0 68000.0 4.9 North\n", "1002 Globex 0.0 45000.0 3.8 East" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Resetting index after sorting\n", "clean_reindexed = sorted_spend.reset_index(drop=True)\n", "print(\"Index reset cleanly from 0 to N-1:\")\n", "display(clean_reindexed.head(3))\n", "\n", "# Setting Customer_ID as the index\n", "df_id_index = clean_reindexed.set_index('Customer_ID')\n", "print(\"\\nDataFrame indexed by Customer_ID:\")\n", "display(df_id_index.head(2))" ] }, { "cell_type": "markdown", "id": "922d397b", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "59fec033", "metadata": {}, "source": [ "\n", "---\n", "# Part IV: Summaries & Group Operations\n", "\n", "## 9. Summary Statistics & Frequencies\n", "\n", "Pandas provides rich aggregate methods to describe numerical and categorical distributions instantly.\n", "\n", "### 9.1 Summary Statistics\n", "By default, aggregate operations automatically ignore `NaN` values:\n", "\n", "| Method | What It Computes |\n", "| :--- | :--- |\n", "| `df['col'].mean()` | Arithmetic average |\n", "| `df['col'].median()` | 50th percentile (robust to outliers) |\n", "| `df['col'].std()` | Sample standard deviation |\n", "| `df['col'].var()` | Sample variance |\n", "| `df['col'].min()`, `max()` | Extreme boundaries |\n", "| `df['col'].quantile(0.75)` | Arbitrary quantile (e.g., 75th percentile) |\n", "| `df['col'].sum()` | Total accumulation |" ] }, { "cell_type": "code", "execution_count": 35, "id": "92dc4d63", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.740750Z", "iopub.status.busy": "2026-10-03T05:03:26.740659Z", "iopub.status.idle": "2026-10-03T05:03:26.746959Z", "shell.execute_reply": "2026-10-03T05:03:26.746701Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mean Spend: $39,333.33\n", "Median Spend: $38,500.00\n", "Standard Deviation: $17,611.55\n", "25th Percentile: $33,625.00\n", "75th Percentile: $43,375.00\n", "Interquartile Range: $9,750.00\n" ] } ], "source": [ "print(f\"Mean Spend: ${df_clean['Annual_Spend'].mean():,.2f}\")\n", "print(f\"Median Spend: ${df_clean['Annual_Spend'].median():,.2f}\")\n", "print(f\"Standard Deviation: ${df_clean['Annual_Spend'].std():,.2f}\")\n", "print(f\"25th Percentile: ${df_clean['Annual_Spend'].quantile(0.25):,.2f}\")\n", "print(f\"75th Percentile: ${df_clean['Annual_Spend'].quantile(0.75):,.2f}\")\n", "print(f\"Interquartile Range: ${df_clean['Annual_Spend'].quantile(0.75) - df_clean['Annual_Spend'].quantile(0.25):,.2f}\")" ] }, { "cell_type": "markdown", "id": "15fa5c0c", "metadata": {}, "source": [ "### 9.2 Categorical Frequencies with `.value_counts()`\n", "`.value_counts()` is one of the most frequently used methods in Pandas. It computes the frequency of each unique value in a Series:\n", "- Pass `normalize=True` to compute relative proportions (percentages).\n", "- Pass `dropna=False` to include counts of missing values." ] }, { "cell_type": "code", "execution_count": 36, "id": "7a52b9c1", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.748179Z", "iopub.status.busy": "2026-10-03T05:03:26.748090Z", "iopub.status.idle": "2026-10-03T05:03:26.751481Z", "shell.execute_reply": "2026-10-03T05:03:26.751234Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Customer Count per Region:\n", "Region\n", "North 2\n", "East 2\n", "Unknown 1\n", "West 1\n", "Name: count, dtype: int64\n", "\n", "Percentage Distribution per Region:\n", "Region\n", "North 33.3%\n", "East 33.3%\n", "Unknown 16.7%\n", "West 16.7%\n", "Name: proportion, dtype: str\n", "\n", "Number of unique regions: 4\n", "Unique region labels: \n", "['North', 'East', 'Unknown', 'West']\n", "Length: 4, dtype: str\n" ] } ], "source": [ "# Frequency counts of Regions\n", "print(\"Customer Count per Region:\")\n", "print(df_clean['Region'].value_counts())\n", "\n", "# Relative proportion percentage\n", "print(\"\\nPercentage Distribution per Region:\")\n", "print((df_clean['Region'].value_counts(normalize=True) * 100).round(1).astype(str) + '%')\n", "\n", "# Unique count and unique values\n", "print(f\"\\nNumber of unique regions: {df_clean['Region'].nunique()}\")\n", "print(f\"Unique region labels: {df_clean['Region'].unique()}\")" ] }, { "cell_type": "markdown", "id": "d56e153c", "metadata": {}, "source": [ "### 9.3 Correlation Matrix with `.corr()`\n", "Examine linear relationships between numerical features using Pearson correlation:" ] }, { "cell_type": "code", "execution_count": 37, "id": "c9cda574", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.752737Z", "iopub.status.busy": "2026-10-03T05:03:26.752627Z", "iopub.status.idle": "2026-10-03T05:03:26.756475Z", "shell.execute_reply": "2026-10-03T05:03:26.756215Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Correlation Matrix:\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", "
Orders_CountAnnual_SpendSatisfaction_Score
Orders_Count1.0000000.3028410.771873
Annual_Spend0.3028411.0000000.282680
Satisfaction_Score0.7718730.2826801.000000
\n", "
" ], "text/plain": [ " Orders_Count Annual_Spend Satisfaction_Score\n", "Orders_Count 1.000000 0.302841 0.771873\n", "Annual_Spend 0.302841 1.000000 0.282680\n", "Satisfaction_Score 0.771873 0.282680 1.000000" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Numerical features correlation matrix\n", "numeric_cols = ['Orders_Count', 'Annual_Spend', 'Satisfaction_Score']\n", "corr_matrix = df_clean[numeric_cols].corr()\n", "print(\"Correlation Matrix:\")\n", "display(corr_matrix)" ] }, { "cell_type": "markdown", "id": "4501c178", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "7f05db81", "metadata": {}, "source": [ "\n", "---\n", "## 10. The GroupBy Engine (Split-Apply-Combine)\n", "\n", "The `groupby()` engine is the centerpiece of tabular data analysis, analogous to SQL's `GROUP BY` clause.\n", "\n", "### 10.1 The Split-Apply-Combine Mental Model\n", "Hadley Wickham coined the term **Split-Apply-Combine** to describe group operations:\n", "1. **SPLIT:** Divide the DataFrame into separate subsets based on keys (e.g. Department).\n", "2. **APPLY:** Compute a summary statistic (e.g. `mean`, `sum`, `count`) independently on each subset.\n", "3. **COMBINE:** Stitch the individual group results back into a clean output DataFrame.\n", "\n", "```\n", " ORIGINAL DATA 1. SPLIT 2. APPLY 3. COMBINE\n", "+------------+-----------+ +------------+-----------+\n", "| Department | Salary | | Department | Salary |\n", "+------------+-----------+ +------------+-----------+\n", "| IT | 88,000 | ---> | IT | 88,000 | ---> mean(IT): 91k ---> +------------+----------+\n", "| HR | 62,000 | | IT | 94,000 | | Department | MeanSal |\n", "| IT | 94,000 | +------------+-----------+ +------------+----------+\n", "| Marketing | 71,000 | | HR | 62,000 | ---> mean(HR): 62k | Finance | 105,000 |\n", "| Finance | 105,000 | +------------+-----------+ | HR | 62,000 |\n", "+------------+-----------+ | Marketing | 71,000 | ---> mean(Mktg): 71k | IT | 91,000 |\n", " +------------+-----------+ | Marketing | 71,000 |\n", " | Finance | 105,000 | ---> mean(Fin): 105k +------------+----------+\n", " +------------+-----------+\n", "```" ] }, { "cell_type": "code", "execution_count": 38, "id": "4f43c087", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.757568Z", "iopub.status.busy": "2026-10-03T05:03:26.757486Z", "iopub.status.idle": "2026-10-03T05:03:26.760816Z", "shell.execute_reply": "2026-10-03T05:03:26.760586Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Average Salary by Department:\n", "Department\n", "Finance 105000.0\n", "HR 62000.0\n", "IT 91000.0\n", "Marketing 71000.0\n", "Name: Salary, dtype: float64\n" ] } ], "source": [ "# Simple single-column aggregation\n", "avg_dept_salary = df_staff.groupby('Department')['Salary'].mean()\n", "print(\"Average Salary by Department:\")\n", "print(avg_dept_salary)" ] }, { "cell_type": "markdown", "id": "6ae43f6a", "metadata": {}, "source": [ "### 10.2 Multiple Aggregations with `.agg()`: Named Aggregations\n", "Often you want to calculate multiple metrics simultaneously (e.g., headcount, average salary, minimum, and maximum salary).\n", "Modern Pandas offers **Named Aggregation** syntax: `agg(New_Col_Name=('Source_Col', 'agg_func'))`. This produces clean, un-nested column names!" ] }, { "cell_type": "code", "execution_count": 39, "id": "198d8cda", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.761858Z", "iopub.status.busy": "2026-10-03T05:03:26.761772Z", "iopub.status.idle": "2026-10-03T05:03:26.770410Z", "shell.execute_reply": "2026-10-03T05:03:26.770106Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Department Summary Table:\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", " \n", " \n", " \n", " \n", " \n", "
DepartmentHeadcountAvg_SalaryMin_SalaryMax_SalaryAvg_Experience
0Finance1105000.010500010500012.0
1HR162000.062000620003.0
2IT291000.088000940008.0
3Marketing171000.071000710004.0
\n", "
" ], "text/plain": [ " Department Headcount Avg_Salary Min_Salary Max_Salary Avg_Experience\n", "0 Finance 1 105000.0 105000 105000 12.0\n", "1 HR 1 62000.0 62000 62000 3.0\n", "2 IT 2 91000.0 88000 94000 8.0\n", "3 Marketing 1 71000.0 71000 71000 4.0" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Clean named aggregations\n", "dept_summary = df_staff.groupby('Department').agg(\n", " Headcount=('Emp_ID', 'count'),\n", " Avg_Salary=('Salary', 'mean'),\n", " Min_Salary=('Salary', 'min'),\n", " Max_Salary=('Salary', 'max'),\n", " Avg_Experience=('Years_Experience', 'mean')\n", ").reset_index()\n", "\n", "print(\"Department Summary Table:\")\n", "display(dept_summary)" ] }, { "cell_type": "markdown", "id": "d666c2de", "metadata": {}, "source": [ "### 10.3 GroupBy `.transform()`: Broadcast Group Metrics to Original Rows\n", "Unlike `.agg()` which collapses rows into group summaries, **`.transform()`** computes a metric per group but returns a Series with the **exact same length and index as the original DataFrame**!\n", "This makes it effortless to compare an individual record against its group average (e.g. \"How much more does Alice earn compared to her department's average?\")." ] }, { "cell_type": "code", "execution_count": 40, "id": "b6bcab8a", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.771513Z", "iopub.status.busy": "2026-10-03T05:03:26.771419Z", "iopub.status.idle": "2026-10-03T05:03:26.776266Z", "shell.execute_reply": "2026-10-03T05:03:26.776053Z" } }, "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", " \n", " \n", " \n", " \n", " \n", " \n", "
NameDepartmentSalaryDept_Avg_SalaryDiff_From_Dept_Avg
0Alice SmithHR6200062000.00.0
1Bob JonesIT8800091000.0-3000.0
2Charlie BrownMarketing7100071000.00.0
3Diana PrinceIT9400091000.03000.0
4Evan WrightFinance105000105000.00.0
\n", "
" ], "text/plain": [ " Name Department Salary Dept_Avg_Salary Diff_From_Dept_Avg\n", "0 Alice Smith HR 62000 62000.0 0.0\n", "1 Bob Jones IT 88000 91000.0 -3000.0\n", "2 Charlie Brown Marketing 71000 71000.0 0.0\n", "3 Diana Prince IT 94000 91000.0 3000.0\n", "4 Evan Wright Finance 105000 105000.0 0.0" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "df_analysis = df_staff.copy()\n", "\n", "# Compute department average salary and attach it directly to each employee's row\n", "df_analysis['Dept_Avg_Salary'] = df_analysis.groupby('Department')['Salary'].transform('mean')\n", "\n", "# Calculate deviation from department average\n", "df_analysis['Diff_From_Dept_Avg'] = df_analysis['Salary'] - df_analysis['Dept_Avg_Salary']\n", "\n", "display(df_analysis[['Name', 'Department', 'Salary', 'Dept_Avg_Salary', 'Diff_From_Dept_Avg']])" ] }, { "cell_type": "markdown", "id": "45b988f2", "metadata": {}, "source": [ "### 10.4 GroupBy `.filter()`: Discard Entire Groups Based on Group Criteria\n", "You can filter out groups that don't meet an aggregate threshold (e.g. \"Only keep departments that have 2 or more employees\"):" ] }, { "cell_type": "code", "execution_count": 41, "id": "accd08a0", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.777332Z", "iopub.status.busy": "2026-10-03T05:03:26.777244Z", "iopub.status.idle": "2026-10-03T05:03:26.781608Z", "shell.execute_reply": "2026-10-03T05:03:26.781374Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Employees belonging to departments with 2+ staff:\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", "
NameDepartmentSalary
1Bob JonesIT88000
3Diana PrinceIT94000
\n", "
" ], "text/plain": [ " Name Department Salary\n", "1 Bob Jones IT 88000\n", "3 Diana Prince IT 94000" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Keep only departments with at least 2 employees\n", "large_depts = df_staff.groupby('Department').filter(lambda group: len(group) >= 2)\n", "print(\"Employees belonging to departments with 2+ staff:\")\n", "display(large_depts[['Name', 'Department', 'Salary']])" ] }, { "cell_type": "markdown", "id": "64609130", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "5f01bd94", "metadata": {}, "source": [ "\n", "---\n", "# Part V: Real-World Techniques\n", "\n", "## 11. Text & String Operations (`.str`)\n", "\n", "Real-world text data is notoriously messy: inconsistent casing, extraneous whitespace, and mixed delimiters.\n", "Pandas provides a dedicated **`.str` accessor** to execute vectorized string operations across entire columns without Python loops.\n", "\n", "Let's inspect messy customer feedback data:" ] }, { "cell_type": "code", "execution_count": 42, "id": "5fc0fd2e", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.782685Z", "iopub.status.busy": "2026-10-03T05:03:26.782588Z", "iopub.status.idle": "2026-10-03T05:03:26.786209Z", "shell.execute_reply": "2026-10-03T05:03:26.785958Z" } }, "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", "
Feedback_IDRaw_CustomerEmailReview
01alice smithALICE@GMAIL.COMGreat product! Fast delivery and great support.
12BOB JONESbob.j@company.orgPackage was damaged upon arrival. Very poor.
23charlie browncharlie_b@yahoo.comExcellent quality, will definitely order again.
34diana princediana@COMPANY.ORGDecent product, but delivery was slow.
\n", "
" ], "text/plain": [ " Feedback_ID Raw_Customer Email \\\n", "0 1 alice smith ALICE@GMAIL.COM \n", "1 2 BOB JONES bob.j@company.org \n", "2 3 charlie brown charlie_b@yahoo.com \n", "3 4 diana prince diana@COMPANY.ORG \n", "\n", " Review \n", "0 Great product! Fast delivery and great support. \n", "1 Package was damaged upon arrival. Very poor. \n", "2 Excellent quality, will definitely order again. \n", "3 Decent product, but delivery was slow. " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "feedback_data = {\n", " 'Feedback_ID': [1, 2, 3, 4],\n", " 'Raw_Customer': [' alice smith ', 'BOB JONES', 'charlie brown ', 'diana prince'],\n", " 'Email': ['ALICE@GMAIL.COM', 'bob.j@company.org', 'charlie_b@yahoo.com', 'diana@COMPANY.ORG'],\n", " 'Review': [\n", " 'Great product! Fast delivery and great support.',\n", " 'Package was damaged upon arrival. Very poor.',\n", " 'Excellent quality, will definitely order again.',\n", " 'Decent product, but delivery was slow.'\n", " ]\n", "}\n", "\n", "df_fb = pd.DataFrame(feedback_data)\n", "display(df_fb)" ] }, { "cell_type": "markdown", "id": "5818affe", "metadata": {}, "source": [ "### 11.1 Cleaning Text: Strip, Lower, Title Case\n", "You can chain string methods together cleanly:" ] }, { "cell_type": "code", "execution_count": 43, "id": "241502eb", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.787259Z", "iopub.status.busy": "2026-10-03T05:03:26.787175Z", "iopub.status.idle": "2026-10-03T05:03:26.791133Z", "shell.execute_reply": "2026-10-03T05:03:26.790880Z" } }, "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", "
Clean_NameClean_Email
0Alice Smithalice@gmail.com
1Bob Jonesbob.j@company.org
2Charlie Browncharlie_b@yahoo.com
3Diana Princediana@company.org
\n", "
" ], "text/plain": [ " Clean_Name Clean_Email\n", "0 Alice Smith alice@gmail.com\n", "1 Bob Jones bob.j@company.org\n", "2 Charlie Brown charlie_b@yahoo.com\n", "3 Diana Prince diana@company.org" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# 1. Clean whitespace and convert names to Title Case\n", "df_fb['Clean_Name'] = df_fb['Raw_Customer'].str.strip().str.title()\n", "\n", "# 2. Standardize emails to lowercase\n", "df_fb['Clean_Email'] = df_fb['Email'].str.strip().str.lower()\n", "\n", "display(df_fb[['Clean_Name', 'Clean_Email']])" ] }, { "cell_type": "markdown", "id": "05f35c00", "metadata": {}, "source": [ "### 11.2 Pattern Matching with `.str.contains()`\n", "Search for substring occurrences or regular expressions. Pass `case=False` for case-insensitive matching:" ] }, { "cell_type": "code", "execution_count": 44, "id": "06cf7511", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.792267Z", "iopub.status.busy": "2026-10-03T05:03:26.792181Z", "iopub.status.idle": "2026-10-03T05:03:26.795804Z", "shell.execute_reply": "2026-10-03T05:03:26.795561Z" } }, "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", "
Clean_NameReviewIs_Positive
0Alice SmithGreat product! Fast delivery and great support.True
1Bob JonesPackage was damaged upon arrival. Very poor.False
2Charlie BrownExcellent quality, will definitely order again.True
3Diana PrinceDecent product, but delivery was slow.False
\n", "
" ], "text/plain": [ " Clean_Name Review Is_Positive\n", "0 Alice Smith Great product! Fast delivery and great support. True\n", "1 Bob Jones Package was damaged upon arrival. Very poor. False\n", "2 Charlie Brown Excellent quality, will definitely order again. True\n", "3 Diana Prince Decent product, but delivery was slow. False" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Flag positive reviews containing 'great' or 'excellent'\n", "pattern = r'great|excellent'\n", "df_fb['Is_Positive'] = df_fb['Review'].str.contains(pattern, case=False, regex=True)\n", "\n", "display(df_fb[['Clean_Name', 'Review', 'Is_Positive']])" ] }, { "cell_type": "markdown", "id": "7125ae92", "metadata": {}, "source": [ "### 11.3 Splitting & Regex Extraction with `expand=True`\n", "- `.str.split('@', expand=True)` splits strings into separate DataFrame columns.\n", "- `.str.extract(pattern)` extracts regex capture groups into named columns." ] }, { "cell_type": "code", "execution_count": 45, "id": "80bed295", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.796942Z", "iopub.status.busy": "2026-10-03T05:03:26.796855Z", "iopub.status.idle": "2026-10-03T05:03:26.800774Z", "shell.execute_reply": "2026-10-03T05:03:26.800539Z" } }, "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", "
Clean_NameClean_EmailEmail_UsernameEmail_Domain
0Alice Smithalice@gmail.comalicegmail.com
1Bob Jonesbob.j@company.orgbob.jcompany.org
2Charlie Browncharlie_b@yahoo.comcharlie_byahoo.com
3Diana Princediana@company.orgdianacompany.org
\n", "
" ], "text/plain": [ " Clean_Name Clean_Email Email_Username Email_Domain\n", "0 Alice Smith alice@gmail.com alice gmail.com\n", "1 Bob Jones bob.j@company.org bob.j company.org\n", "2 Charlie Brown charlie_b@yahoo.com charlie_b yahoo.com\n", "3 Diana Prince diana@company.org diana company.org" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Extract username and domain from email\n", "split_email = df_fb['Clean_Email'].str.split('@', expand=True)\n", "split_email.columns = ['Email_Username', 'Email_Domain']\n", "\n", "# Combine with main DataFrame\n", "df_fb_expanded = pd.concat([df_fb[['Clean_Name', 'Clean_Email']], split_email], axis=1)\n", "display(df_fb_expanded)" ] }, { "cell_type": "markdown", "id": "8c9c66c3", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "8efd2036", "metadata": {}, "source": [ "\n", "---\n", "## 12. Working with Dates & Times (`.dt`)\n", "\n", "Date and time information frequently arrives as plain string text (`'2026-03-15'`). Converting text into proper datetime objects is crucial for chronological sorting, time math, and calendar feature engineering.\n", "\n", "### 12.1 Parsing Datetimes with `pd.to_datetime()`\n", "`pd.to_datetime()` automatically handles most ISO 8601 string formats. Specifying the exact `format` argument significantly speeds up parsing on large files:" ] }, { "cell_type": "code", "execution_count": 46, "id": "5e63cda9", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.801892Z", "iopub.status.busy": "2026-10-03T05:03:26.801807Z", "iopub.status.idle": "2026-10-03T05:03:26.807840Z", "shell.execute_reply": "2026-10-03T05:03:26.807594Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before conversion:\n", "Order_ID int64\n", "Order_Timestamp str\n", "Delivery_Timestamp str\n", "Total_Amount float64\n", "dtype: object\n", "\n", "After conversion:\n", "Order_ID int64\n", "Order_Timestamp datetime64[us]\n", "Delivery_Timestamp datetime64[us]\n", "Total_Amount float64\n", "dtype: object\n" ] } ], "source": [ "order_records = {\n", " 'Order_ID': [5001, 5002, 5003, 5004, 5005],\n", " 'Order_Timestamp': [\n", " '2026-01-15 09:30:00',\n", " '2026-01-18 14:15:00',\n", " '2026-02-05 18:45:00',\n", " '2026-03-12 11:20:00',\n", " '2026-03-29 16:50:00'\n", " ],\n", " 'Delivery_Timestamp': [\n", " '2026-01-18 12:00:00',\n", " '2026-01-22 17:30:00',\n", " '2026-02-07 10:15:00',\n", " '2026-03-16 15:00:00',\n", " '2026-04-03 09:30:00'\n", " ],\n", " 'Total_Amount': [145.0, 230.5, 89.0, 412.0, 310.0]\n", "}\n", "\n", "df_orders = pd.DataFrame(order_records)\n", "print(\"Before conversion:\")\n", "print(df_orders.dtypes)\n", "\n", "# Convert strings to datetime64[ns]\n", "df_orders['Order_Timestamp'] = pd.to_datetime(df_orders['Order_Timestamp'])\n", "df_orders['Delivery_Timestamp'] = pd.to_datetime(df_orders['Delivery_Timestamp'])\n", "\n", "print(\"\\nAfter conversion:\")\n", "print(df_orders.dtypes)" ] }, { "cell_type": "markdown", "id": "c4c2365f", "metadata": {}, "source": [ "### 12.2 Extracting Calendar Properties with the `.dt` Accessor\n", "Similar to `.str`, the **`.dt` accessor** exposes calendar properties:\n", "- `.dt.year`, `.dt.month`, `.dt.day`\n", "- `.dt.day_name()`, `.dt.month_name()`\n", "- `.dt.quarter`, `.dt.dayofweek` (0 = Monday, 6 = Sunday)\n", "- `.dt.is_month_end`, `.dt.is_weekend`" ] }, { "cell_type": "code", "execution_count": 47, "id": "7364ff07", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.808931Z", "iopub.status.busy": "2026-10-03T05:03:26.808840Z", "iopub.status.idle": "2026-10-03T05:03:26.813874Z", "shell.execute_reply": "2026-10-03T05:03:26.813640Z" } }, "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", " \n", " \n", " \n", " \n", " \n", " \n", "
Order_IDOrder_TimestampOrder_MonthOrder_Day_NameIs_Weekend
050012026-01-15 09:30:00JanuaryThursdayFalse
150022026-01-18 14:15:00JanuarySundayTrue
250032026-02-05 18:45:00FebruaryThursdayFalse
350042026-03-12 11:20:00MarchThursdayFalse
450052026-03-29 16:50:00MarchSundayTrue
\n", "
" ], "text/plain": [ " Order_ID Order_Timestamp Order_Month Order_Day_Name Is_Weekend\n", "0 5001 2026-01-15 09:30:00 January Thursday False\n", "1 5002 2026-01-18 14:15:00 January Sunday True\n", "2 5003 2026-02-05 18:45:00 February Thursday False\n", "3 5004 2026-03-12 11:20:00 March Thursday False\n", "4 5005 2026-03-29 16:50:00 March Sunday True" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Calendar feature engineering\n", "df_orders['Order_Year'] = df_orders['Order_Timestamp'].dt.year\n", "df_orders['Order_Month'] = df_orders['Order_Timestamp'].dt.month_name()\n", "df_orders['Order_Day_Name'] = df_orders['Order_Timestamp'].dt.day_name()\n", "df_orders['Is_Weekend'] = df_orders['Order_Timestamp'].dt.dayofweek >= 5\n", "\n", "display(df_orders[['Order_ID', 'Order_Timestamp', 'Order_Month', 'Order_Day_Name', 'Is_Weekend']])" ] }, { "cell_type": "markdown", "id": "32ef30c8", "metadata": {}, "source": [ "### 12.3 Date Arithmetic & Timedeltas\n", "Subtracting two datetime columns produces a **`Timedelta`** Series, allowing exact duration measurements:" ] }, { "cell_type": "code", "execution_count": 48, "id": "11a6d71b", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.815024Z", "iopub.status.busy": "2026-10-03T05:03:26.814937Z", "iopub.status.idle": "2026-10-03T05:03:26.819944Z", "shell.execute_reply": "2026-10-03T05:03:26.819663Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Order Delivery Durations:\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", "
Order_IDDelivery_DurationDuration_Days
050013 days 02:30:003.104167
150024 days 03:15:004.135417
250031 days 15:30:001.645833
350044 days 03:40:004.152778
450054 days 16:40:004.694444
\n", "
" ], "text/plain": [ " Order_ID Delivery_Duration Duration_Days\n", "0 5001 3 days 02:30:00 3.104167\n", "1 5002 4 days 03:15:00 4.135417\n", "2 5003 1 days 15:30:00 1.645833\n", "3 5004 4 days 03:40:00 4.152778\n", "4 5005 4 days 16:40:00 4.694444" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Average delivery duration: 3.55 days\n" ] } ], "source": [ "# Calculate delivery duration\n", "df_orders['Delivery_Duration'] = df_orders['Delivery_Timestamp'] - df_orders['Order_Timestamp']\n", "\n", "# Extract fractional days or total hours\n", "df_orders['Duration_Days'] = df_orders['Delivery_Duration'].dt.total_seconds() / 86400\n", "\n", "print(\"Order Delivery Durations:\")\n", "display(df_orders[['Order_ID', 'Delivery_Duration', 'Duration_Days']])\n", "print(f\"\\nAverage delivery duration: {df_orders['Duration_Days'].mean():.2f} days\")" ] }, { "cell_type": "markdown", "id": "d0e44eb4", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "1ed3ca87", "metadata": {}, "source": [ "\n", "---\n", "## 13. Combining Datasets: Concat & Merge\n", "\n", "In production, data is normalized across multiple tables. Pandas provides two core mechanisms for combining data:\n", "1. **`pd.concat()`**: Stacking DataFrames on top of each other (rows) or side-by-side (columns).\n", "2. **`pd.merge()`**: Relational SQL-style joins matching on common key columns.\n", "\n", "### 13.1 Concatenation: Stacking DataFrames\n", "Use `pd.concat([df1, df2], axis=0)` to combine monthly or quarterly files that share the same schema:" ] }, { "cell_type": "code", "execution_count": 49, "id": "3830f42d", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.821103Z", "iopub.status.busy": "2026-10-03T05:03:26.821015Z", "iopub.status.idle": "2026-10-03T05:03:26.824694Z", "shell.execute_reply": "2026-10-03T05:03:26.824439Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Combined Sales (Row-stacked):\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", "
ProductRevenue
0Laptop12000
1Phone8000
2Laptop14000
3Tablet6000
\n", "
" ], "text/plain": [ " Product Revenue\n", "0 Laptop 12000\n", "1 Phone 8000\n", "2 Laptop 14000\n", "3 Tablet 6000" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Monthly sales tables\n", "jan_sales = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Revenue': [12000, 8000]})\n", "feb_sales = pd.DataFrame({'Product': ['Laptop', 'Tablet'], 'Revenue': [14000, 6000]})\n", "\n", "# Stack rows vertically (axis=0)\n", "combined_sales = pd.concat([jan_sales, feb_sales], ignore_index=True)\n", "print(\"Combined Sales (Row-stacked):\")\n", "display(combined_sales)" ] }, { "cell_type": "markdown", "id": "20a13237", "metadata": {}, "source": [ "### 13.2 Merging: Relational SQL Joins\n", "`pd.merge(left, right, on='Key_Col', how='inner'|'left'|'right'|'outer')`\n", "\n", "```\n", " VISUAL GUIDE TO PANDAS MERGES\n", "+-------------------+--------------------+-------------------+--------------------+\n", "| INNER JOIN | LEFT JOIN | RIGHT JOIN | OUTER JOIN |\n", "| how='inner' | how='left' | how='right' | how='outer' |\n", "+-------------------+--------------------+-------------------+--------------------+\n", "| Only keys present | ALL rows from left | ALL rows from right| ALL rows from both|\n", "| in BOTH tables. | table. Unmatched | table. Unmatched | tables. Missing |\n", "| | right keys get NaN | left keys get NaN | values get NaN |\n", "+-------------------+--------------------+-------------------+--------------------+\n", "```" ] }, { "cell_type": "code", "execution_count": 50, "id": "33842ec7", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.825846Z", "iopub.status.busy": "2026-10-03T05:03:26.825762Z", "iopub.status.idle": "2026-10-03T05:03:26.831142Z", "shell.execute_reply": "2026-10-03T05:03:26.830908Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Customers Table:\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", "
Cust_IDCompany
01Acme Corp
12Globex
23Soylent
34Initech
\n", "
" ], "text/plain": [ " Cust_ID Company\n", "0 1 Acme Corp\n", "1 2 Globex\n", "2 3 Soylent\n", "3 4 Initech" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Orders Table:\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", "
Order_IDCust_IDAmount
09011450.0
190221200.0
29031310.0
39045890.0
\n", "
" ], "text/plain": [ " Order_ID Cust_ID Amount\n", "0 901 1 450.0\n", "1 902 2 1200.0\n", "2 903 1 310.0\n", "3 904 5 890.0" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Table 1: Customers\n", "customers_tbl = pd.DataFrame({\n", " 'Cust_ID': [1, 2, 3, 4],\n", " 'Company': ['Acme Corp', 'Globex', 'Soylent', 'Initech']\n", "})\n", "\n", "# Table 2: Orders (Note: Cust_ID 5 is an unregistered customer; Cust_ID 4 has placed no orders)\n", "orders_tbl = pd.DataFrame({\n", " 'Order_ID': [901, 902, 903, 904],\n", " 'Cust_ID': [1, 2, 1, 5],\n", " 'Amount': [450.0, 1200.0, 310.0, 890.0]\n", "})\n", "\n", "print(\"Customers Table:\")\n", "display(customers_tbl)\n", "print(\"\\nOrders Table:\")\n", "display(orders_tbl)" ] }, { "cell_type": "code", "execution_count": 51, "id": "508248c8", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.832239Z", "iopub.status.busy": "2026-10-03T05:03:26.832155Z", "iopub.status.idle": "2026-10-03T05:03:26.843956Z", "shell.execute_reply": "2026-10-03T05:03:26.843716Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--- Inner Join (Only Matching Customers & Orders) ---\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", "
Cust_IDCompanyOrder_IDAmount
01Acme Corp901450.0
11Acme Corp903310.0
22Globex9021200.0
\n", "
" ], "text/plain": [ " Cust_ID Company Order_ID Amount\n", "0 1 Acme Corp 901 450.0\n", "1 1 Acme Corp 903 310.0\n", "2 2 Globex 902 1200.0" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "--- Left Join (Preserves All Customers) ---\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", " \n", " \n", "
Cust_IDCompanyOrder_IDAmount
01Acme Corp901.0450.0
11Acme Corp903.0310.0
22Globex902.01200.0
33SoylentNaNNaN
44InitechNaNNaN
\n", "
" ], "text/plain": [ " Cust_ID Company Order_ID Amount\n", "0 1 Acme Corp 901.0 450.0\n", "1 1 Acme Corp 903.0 310.0\n", "2 2 Globex 902.0 1200.0\n", "3 3 Soylent NaN NaN\n", "4 4 Initech NaN NaN" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "--- Outer Join (Full Union of Both Tables) ---\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Cust_IDCompanyOrder_IDAmount
01Acme Corp901.0450.0
11Acme Corp903.0310.0
22Globex902.01200.0
33SoylentNaNNaN
44InitechNaNNaN
55NaN904.0890.0
\n", "
" ], "text/plain": [ " Cust_ID Company Order_ID Amount\n", "0 1 Acme Corp 901.0 450.0\n", "1 1 Acme Corp 903.0 310.0\n", "2 2 Globex 902.0 1200.0\n", "3 3 Soylent NaN NaN\n", "4 4 Initech NaN NaN\n", "5 5 NaN 904.0 890.0" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# 1. Inner Join (Matches only)\n", "inner_join = pd.merge(customers_tbl, orders_tbl, on='Cust_ID', how='inner')\n", "print(\"--- Inner Join (Only Matching Customers & Orders) ---\")\n", "display(inner_join)\n", "\n", "# 2. Left Join (Keep all customers)\n", "left_join = pd.merge(customers_tbl, orders_tbl, on='Cust_ID', how='left')\n", "print(\"\\n--- Left Join (Preserves All Customers) ---\")\n", "display(left_join)\n", "\n", "# 3. Outer Join (Full union)\n", "outer_join = pd.merge(customers_tbl, orders_tbl, on='Cust_ID', how='outer')\n", "print(\"\\n--- Outer Join (Full Union of Both Tables) ---\")\n", "display(outer_join)" ] }, { "cell_type": "markdown", "id": "eec6bbc8", "metadata": {}, "source": [ "### 13.3 Detecting Non-Matches with the Anti-Join Pattern\n", "To find customers who have NEVER placed an order, perform a `left` merge with `indicator=True`:" ] }, { "cell_type": "code", "execution_count": 52, "id": "08fb579f", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.845084Z", "iopub.status.busy": "2026-10-03T05:03:26.844997Z", "iopub.status.idle": "2026-10-03T05:03:26.851639Z", "shell.execute_reply": "2026-10-03T05:03:26.851371Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Customers who have NEVER placed an order (Anti-Join):\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", "
Cust_IDCompany
33Soylent
44Initech
\n", "
" ], "text/plain": [ " Cust_ID Company\n", "3 3 Soylent\n", "4 4 Initech" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "anti_join_check = pd.merge(customers_tbl, orders_tbl, on='Cust_ID', how='left', indicator=True)\n", "unmatched_customers = anti_join_check[anti_join_check['_merge'] == 'left_only']\n", "\n", "print(\"Customers who have NEVER placed an order (Anti-Join):\")\n", "display(unmatched_customers[['Cust_ID', 'Company']])" ] }, { "cell_type": "markdown", "id": "7a288680", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "6eeedff9", "metadata": {}, "source": [ "\n", "---\n", "## 14. Reshaping: Pivot Tables & Melt\n", "\n", "Data is often formatted for human readability (wide tables with months across columns) rather than machine learning (tidy, tall tables where each row is an observation).\n", "\n", "### 14.1 Pivot Tables: 2-Dimensional Summaries\n", "`df.pivot_table()` is identical to Excel pivot tables:\n", "- `index`: Column to use as row headers.\n", "- `columns`: Column to use as column headers.\n", "- `values`: Column to aggregate.\n", "- `aggfunc`: Function to aggregate with (default is `'mean'`, can use `'sum'`, `'count'`).\n", "- `margins=True`: Appends subtotal/total rows and columns." ] }, { "cell_type": "code", "execution_count": 53, "id": "85bd6093", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.852875Z", "iopub.status.busy": "2026-10-03T05:03:26.852768Z", "iopub.status.idle": "2026-10-03T05:03:26.864945Z", "shell.execute_reply": "2026-10-03T05:03:26.864700Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sales Pivot Table (Store by Department):\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", "
DepartmentClothingElectronicsTotal
Store
Downtown80003300041000
Suburbs205001200032500
Total285004500073500
\n", "
" ], "text/plain": [ "Department Clothing Electronics Total\n", "Store \n", "Downtown 8000 33000 41000\n", "Suburbs 20500 12000 32500\n", "Total 28500 45000 73500" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "store_sales = pd.DataFrame({\n", " 'Store': ['Downtown', 'Suburbs', 'Downtown', 'Suburbs', 'Downtown', 'Suburbs'],\n", " 'Department': ['Electronics', 'Electronics', 'Clothing', 'Clothing', 'Electronics', 'Clothing'],\n", " 'Quarter': ['Q1', 'Q1', 'Q1', 'Q1', 'Q2', 'Q2'],\n", " 'Sales': [15000, 12000, 8000, 9500, 18000, 11000]\n", "})\n", "\n", "# Pivot Table: Store vs Department Total Sales\n", "pivot_table_res = store_sales.pivot_table(\n", " index='Store',\n", " columns='Department',\n", " values='Sales',\n", " aggfunc='sum',\n", " margins=True,\n", " margins_name='Total'\n", ")\n", "\n", "print(\"Sales Pivot Table (Store by Department):\")\n", "display(pivot_table_res)" ] }, { "cell_type": "markdown", "id": "450ea0b3", "metadata": {}, "source": [ "### 14.2 Unpivoting with `pd.melt()` (Wide to Long Format)\n", "Machine learning libraries (Scikit-Learn, PyTorch) require **tidy data**, where each column represents a single variable.\n", "`pd.melt()` unpivots a wide table into a tall, tidy format:" ] }, { "cell_type": "code", "execution_count": 54, "id": "0c04e2ac", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.866108Z", "iopub.status.busy": "2026-10-03T05:03:26.866004Z", "iopub.status.idle": "2026-10-03T05:03:26.872777Z", "shell.execute_reply": "2026-10-03T05:03:26.872523Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wide Format Table:\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", "
RegionJan_RevFeb_RevMar_Rev
0North100001150013000
1South120001250014000
\n", "
" ], "text/plain": [ " Region Jan_Rev Feb_Rev Mar_Rev\n", "0 North 10000 11500 13000\n", "1 South 12000 12500 14000" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Tidy Long Format Table (via pd.melt):\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", " \n", " \n", "
RegionMonthRevenue
0NorthJan_Rev10000
1SouthJan_Rev12000
2NorthFeb_Rev11500
3SouthFeb_Rev12500
4NorthMar_Rev13000
5SouthMar_Rev14000
\n", "
" ], "text/plain": [ " Region Month Revenue\n", "0 North Jan_Rev 10000\n", "1 South Jan_Rev 12000\n", "2 North Feb_Rev 11500\n", "3 South Feb_Rev 12500\n", "4 North Mar_Rev 13000\n", "5 South Mar_Rev 14000" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Wide table (Months are column headers)\n", "wide_revenue = pd.DataFrame({\n", " 'Region': ['North', 'South'],\n", " 'Jan_Rev': [10000, 12000],\n", " 'Feb_Rev': [11500, 12500],\n", " 'Mar_Rev': [13000, 14000]\n", "})\n", "\n", "print(\"Wide Format Table:\")\n", "display(wide_revenue)\n", "\n", "# Melt into long tidy format\n", "tidy_revenue = pd.melt(\n", " wide_revenue,\n", " id_vars=['Region'],\n", " value_vars=['Jan_Rev', 'Feb_Rev', 'Mar_Rev'],\n", " var_name='Month',\n", " value_name='Revenue'\n", ")\n", "\n", "print(\"\\nTidy Long Format Table (via pd.melt):\")\n", "display(tidy_revenue)" ] }, { "cell_type": "markdown", "id": "45b5f388", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "04d7eaa6", "metadata": {}, "source": [ "\n", "---\n", "## 15. Performance, Gotchas & Cheat Sheet\n", "\n", "### 15.1 The Dreaded `SettingWithCopyWarning`\n", "Every Pandas user encounters this warning:\n", "`SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.`\n", "\n", "#### Why does it occur?\n", "It happens during **chained assignment** like `df[df['Score'] > 80]['Passed'] = True`:\n", "- Step 1: `df[df['Score'] > 80]` extracts a subset.\n", "- Step 2: `['Passed'] = True` attempts to write to that subset.\n", "- The Problem: Pandas cannot determine whether the subset is a **view** (sharing memory with the original) or a **copy** (an independent buffer). If it's a copy, your assignment is silently lost!\n", "\n", "#### The Two Best Solutions:\n", "1. **If you want to modify the original DataFrame:** Use `.loc[row_condition, 'col'] = value`.\n", "2. **If you want a standalone new DataFrame:** Explicitly call `.copy()`." ] }, { "cell_type": "code", "execution_count": 55, "id": "f6cf99e9", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.873912Z", "iopub.status.busy": "2026-10-03T05:03:26.873806Z", "iopub.status.idle": "2026-10-03T05:03:26.880163Z", "shell.execute_reply": "2026-10-03T05:03:26.879862Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Safely modified original using .loc:\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", "
StudentScoreStatus
0Amy85Pass
1Ben62Fail
2Chris91Pass
\n", "
" ], "text/plain": [ " Student Score Status\n", "0 Amy 85 Pass\n", "1 Ben 62 Fail\n", "2 Chris 91 Pass" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Safely created independent subset using .copy():\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", "
StudentScoreStatusHonors
0Amy85PassFalse
2Chris91PassTrue
\n", "
" ], "text/plain": [ " Student Score Status Honors\n", "0 Amy 85 Pass False\n", "2 Chris 91 Pass True" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "sample_scores = pd.DataFrame({'Student': ['Amy', 'Ben', 'Chris'], 'Score': [85, 62, 91]})\n", "\n", "# BEST PRACTICE 1: Use .loc to modify the original table directly\n", "sample_scores.loc[sample_scores['Score'] >= 70, 'Status'] = 'Pass'\n", "sample_scores.loc[sample_scores['Score'] < 70, 'Status'] = 'Fail'\n", "print(\"Safely modified original using .loc:\")\n", "display(sample_scores)\n", "\n", "# BEST PRACTICE 2: Use .copy() to create an independent subset\n", "passed_students = sample_scores[sample_scores['Status'] == 'Pass'].copy()\n", "passed_students['Honors'] = passed_students['Score'] >= 90\n", "print(\"\\nSafely created independent subset using .copy():\")\n", "display(passed_students)" ] }, { "cell_type": "markdown", "id": "02d42ec0", "metadata": {}, "source": [ "### 15.2 Execution Speed Benchmark: Vectorization vs `.apply()` vs `for` Loop\n", "Never iterate through rows using Python `for` loops or `df.iterrows()` when a vectorized method exists.\n", "Let's benchmark on **500,000 records**:" ] }, { "cell_type": "code", "execution_count": 56, "id": "f730368a", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:26.881339Z", "iopub.status.busy": "2026-10-03T05:03:26.881250Z", "iopub.status.idle": "2026-10-03T05:03:27.057355Z", "shell.execute_reply": "2026-10-03T05:03:27.057055Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "🚀 Vectorized computation (500k): 0.0024 seconds\n", "🐢 .apply(axis=1) (extrapolated): 1.6382 seconds\n", "⚡ Vectorization is 668.9x faster!\n" ] } ], "source": [ "import time\n", "\n", "# Create benchmark dataset of 500,000 rows\n", "N = 500_000\n", "bench_df = pd.DataFrame({\n", " 'Base_Price': np.random.uniform(20.0, 200.0, size=N),\n", " 'Tax_Rate': np.random.uniform(0.05, 0.20, size=N)\n", "})\n", "\n", "# 1. Vectorized Arithmetic (Fastest, C/SIMD speed)\n", "t0 = time.perf_counter()\n", "res_vec = bench_df['Base_Price'] * (1 + bench_df['Tax_Rate'])\n", "t1 = time.perf_counter()\n", "t_vectorized = t1 - t0\n", "\n", "# 2. .apply(axis=1) with Python Lambda (Interpreted in Python)\n", "# Benchmarked on 50,000 rows and extrapolated to 500k to save execution time\n", "t0 = time.perf_counter()\n", "_ = bench_df.iloc[:50_000].apply(lambda row: row['Base_Price'] * (1 + row['Tax_Rate']), axis=1)\n", "t1 = time.perf_counter()\n", "t_apply = (t1 - t0) * 10\n", "\n", "print(f\"🚀 Vectorized computation (500k): {t_vectorized:.4f} seconds\")\n", "print(f\"🐢 .apply(axis=1) (extrapolated): {t_apply:.4f} seconds\")\n", "print(f\"⚡ Vectorization is {t_apply / t_vectorized:.1f}x faster!\")" ] }, { "cell_type": "markdown", "id": "14bd238b", "metadata": {}, "source": [ "### 15.3 Memory Optimization: The Power of Categorical Dtypes\n", "By default, text columns are stored as `object` (arrays of pointers to Python string heap objects).\n", "If a text column contains repeated values (e.g. Gender, Country, Department, Status), converting it to `'category'` stores the distinct strings once in a lookup table and replaces the column with tiny integers (e.g. `int8`)." ] }, { "cell_type": "code", "execution_count": 57, "id": "bb21ca43", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:03:27.058682Z", "iopub.status.busy": "2026-10-03T05:03:27.058586Z", "iopub.status.idle": "2026-10-03T05:03:27.114655Z", "shell.execute_reply": "2026-10-03T05:03:27.114360Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "📦 Object dtype memory: 10,999,276 bytes\n", "⚡ Category dtype memory: 200,407 bytes\n", "🎉 Memory reduced by 54.9x!\n" ] } ], "source": [ "# 200,000 rows with repeated city names\n", "n_records = 200_000\n", "cities = np.random.choice(['New York', 'London', 'Tokyo', 'Paris', 'Sydney'], size=n_records)\n", "df_mem = pd.DataFrame({'City': cities})\n", "\n", "# Measure memory\n", "mem_object = df_mem['City'].memory_usage(deep=True)\n", "df_mem['City'] = df_mem['City'].astype('category')\n", "mem_category = df_mem['City'].memory_usage(deep=True)\n", "\n", "print(f\"📦 Object dtype memory: {mem_object:>10,} bytes\")\n", "print(f\"⚡ Category dtype memory: {mem_category:>10,} bytes\")\n", "print(f\"🎉 Memory reduced by {mem_object / mem_category:.1f}x!\")" ] }, { "cell_type": "markdown", "id": "6b83961d", "metadata": {}, "source": [ "---\n", "\n", "## 🏆 Comprehensive High-Frequency Cheat Sheet\n", "\n", "| Task | Syntax / Method | Example |\n", "| :--- | :--- | :--- |\n", "| **Inspect Data** | `head()`, `tail()`, `info()`, `describe()` | `df.info()`, `df.describe()` |\n", "| **Select Column(s)** | `df['col']` (Series) / `df[['c1', 'c2']]` (DataFrame) | `df[['Age', 'Salary']]` |\n", "| **Select by Position** | `df.iloc[row_idx, col_idx]` | `df.iloc[0:5, 1:4]` |\n", "| **Select by Label** | `df.loc[row_label, col_label]` | `df.loc['Alice':'Diana', 'Salary']` |\n", "| **Filter by Condition** | `df[(cond1) & (cond2)]` | `df[(df['Age'] > 25) & (df['Remote'])]` |\n", "| **Membership Filter** | `df['col'].isin([val1, val2])` | `df[df['Dept'].isin(['HR', 'IT'])]` |\n", "| **Range Filter** | `df['col'].between(low, high)` | `df[df['Salary'].between(60k, 90k)]` |\n", "| **Add / Modify Column** | `df['new'] = expression` | `df['Bonus'] = df['Salary'] * 0.1` |\n", "| **Rename Column** | `df.rename(columns={'old': 'new'})` | `df.rename(columns={'id': 'user_id'})` |\n", "| **Drop Column / Row** | `df.drop(columns=[...])` / `df.drop(index=[...])` | `df.drop(columns=['unneeded_col'])` |\n", "| **Check Missing Data** | `df.isna().sum()` | `df.isna().sum()` |\n", "| **Drop Missing Data** | `df.dropna(subset=[...])` | `df.dropna(subset=['critical_col'])` |\n", "| **Fill Missing Data** | `df['col'].fillna(val)` | `df['Salary'].fillna(df['Salary'].median())` |\n", "| **Sort Values** | `df.sort_values(by=..., ascending=...)` | `df.sort_values(by='Salary', ascending=False)` |\n", "| **Reset Index** | `df.reset_index(drop=True)` | `df.reset_index(drop=True)` |\n", "| **Value Counts** | `df['col'].value_counts(normalize=True)` | `df['Department'].value_counts()` |\n", "| **GroupBy & Agg** | `df.groupby('key').agg(...)` | `df.groupby('dept').agg(avg_sal=('sal', 'mean'))` |\n", "| **Transform Group** | `df.groupby('key')['col'].transform('mean')` | `df['dept_avg'] = df.groupby('dept')['sal'].transform('mean')` |\n", "| **Clean Strings** | `df['text'].str.strip().str.title()` | `df['name'].str.strip().str.title()` |\n", "| **Date Conversion** | `pd.to_datetime(df['date'])` | `df['date'] = pd.to_datetime(df['date'])` |\n", "| **Date Properties** | `df['date'].dt.year`, `.dt.day_name()` | `df['weekday'] = df['date'].dt.day_name()` |\n", "| **Stack Tables** | `pd.concat([df1, df2], ignore_index=True)` | `pd.concat([q1, q2], axis=0)` |\n", "| **Join Tables** | `pd.merge(df1, df2, on='key', how='left')` | `pd.merge(users, orders, on='id')` |\n", "| **Pivot Table** | `df.pivot_table(index=..., columns=..., values=...)`| `df.pivot_table(index='dept', columns='year', values='sal')` |\n", "| **Melt Wide to Long** | `pd.melt(df, id_vars=[...], value_vars=[...])` | `pd.melt(df, id_vars=['id'], var_name='month')` |\n", "\n", "---\n", "### 🎯 Practice What You Have Learned!\n", "Put your skills into practice with the companion exercise notebooks:\n", "- 🏋️ [02_pandas_exercise_1.ipynb](file:///Users/Inz_mac/Developer/ML/my-note/pandas/02_pandas_exercise_1.ipynb): 20 progressive practice problems.\n", "- 💡 [03_pandas_exercise_1_solutions.ipynb](file:///Users/Inz_mac/Developer/ML/my-note/pandas/03_pandas_exercise_1_solutions.ipynb): Verified solutions with pre-executed outputs.\n", "- 🚀 [04_pandas_exercise_2.ipynb](file:///Users/Inz_mac/Developer/ML/my-note/pandas/04_pandas_exercise_2.ipynb): 15 real-world data engineering and analytics scenario challenges.\n", "- 💡 [05_pandas_exercise_2_solutions.ipynb](file:///Users/Inz_mac/Developer/ML/my-note/pandas/05_pandas_exercise_2_solutions.ipynb): Full scenario solutions with pre-executed outputs." ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "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 }