2. Tabular Data Mastery with Pandas
Pandas Series, DataFrames, loc/iloc & Filtering
Master Pandas' core tabular structures: create Series and DataFrames, inspect shapes and types with .info() and .describe(), slice accurately with .loc vs .iloc, and filter rows.
- Create and inspect Pandas Series and DataFrames using .head(), .info(), and .describe()
- Select rows and columns unambiguously with label-based .loc[] and position-based .iloc[]
- Filter rows and derive new columns cleanly without SettingWithCopyWarning
NumPy arrays excel at uniform numeric matrices, but real business data isn't all numbers. An enrollment export from an academy platform mixes student names (str), tracks (category/str), hours studied (int or float), timestamps (datetime64), and completion flags (bool).
Pandas (import pandas as pd) builds labeled, column-typed tables right on top of NumPy—giving you SQL-like filtering and Excel-like columns inside reproducible Python scripts.
1. Core Mental Model: Series vs DataFrame
| Index | student | track | hours |
|---|---|---|---|
| 0 | Maya | Data | 14 |
| 1 | Liam | Backend | 9 |
axis=0 collapses vertically down rows (one result per column); axis=1 collapses horizontally across columns (one result per row).
Think of a DataFrame as a dictionary of aligned columns sharing one row index, where each individual column is a Series:
Series: A 1D labeled array (pd.Series([14, 9, 18], name="hours")) holding one data type (dtype).DataFrame: A 2D table ofSeriesobjects sharing row index labels (0, 1, 2, ...or custom IDs/dates).
First 60 Seconds on Any New Dataset
Whenever you load a table, inspect its structure before writing a single filter:
import pandas as pd
df = pd.DataFrame([
{"student": "Maya", "track": "Data", "hours": 14, "completed": True},
{"student": "Liam", "track": "Backend", "hours": 9, "completed": False},
{"student": "Sam", "track": "Data", "hours": 18, "completed": True},
])
print(df.head(2)) # Preview first 2 rows visually
print(df.shape) # (3, 4) -> 3 rows, 4 columns
df.info() # Non-null counts + exact dtype per column + memory usage
print(df.describe()) # Count, mean, std, min, quartiles, max for numeric columnsdf.info() immediately reveals two silent killers: columns with unexpected null gaps, and numbers accidentally loaded as object (strings) because a single cell contained "$1,200" or "N/A".
2. .loc[] vs .iloc[]: Labels vs Positions
One of the top sources of Pandas bugs is mixing up label indexing and integer-position indexing—especially after sorting or filtering rows, when row index labels (0, 2, 7) no longer match row positions (0, 1, 2)!
| Feature | .loc[rows, cols] | .iloc[rows, cols] |
|---|---|---|
| Lookup style | Label-based (row index names & column names) | Position-based (0-based integer offsets) |
| Boolean masks | Yes (df.loc[df["hours"] > 10, ["student"]]) | Not directly on Series masks |
| Slice end behavior | Inclusive (df.loc[0:2] includes label 2) | Exclusive (df.iloc[0:2] stops before 2) |
| Typical use | Business filters, named column subsets, updates | First/last N rows (df.iloc[:5, :3]) |
Line-by-Line Walkthrough of Safe Filtering
# Goal: get student & hours for learners who completed the Data track
mask = df["completed"] & (df["track"] == "Data")
active_data = df.loc[mask, ["student", "hours"]]
# Positional slice: first 2 rows, first 2 columns
top_corner = df.iloc[:2, :2]Trace what happens step by step:
df["completed"]is already a booleanSeries([True, False, True]).(df["track"] == "Data")produces[True, False, True].- Bitwise
&combines them element-wise ([True, False, True]). .loc[mask, ["student", "hours"]]keeps onlyTruerows and only those two columns in one atomic lookup.
3. Derived Columns & Avoiding SettingWithCopyWarning
Suppose you filter df down to Data learners and then try to add or modify a column on that subset, or write chained brackets df[mask]["bonus"] = 5:
# BAD: Chained assignment! Modifies a temporary slice copy or warns loudly
df[df["hours"] > 10]["bonus"] = 5 # SettingWithCopyWarning!
# GOOD Option 1: Single .loc assignment directly on df
df.loc[df["hours"] > 10, "bonus"] = 5
# GOOD Option 2: Explicit .copy() before transforming a filtered subset
data_only = df.loc[df["track"] == "Data"].copy()
data_only["bonus"] = 5
# GOOD Option 3: Functional .assign() returning a brand-new DataFrame
enriched = df.assign(
weekly_pace=df["hours"] / 2,
is_power_learner=df["hours"] >= 12,
)In df[df["hours"] > 10]["bonus"] = 5, Python runs two separate operations: first __getitem__ (df[...]) may return a temporary copy, and then __setitem__ (["bonus"] = 5) mutates that throwaway copy—leaving your original df completely unchanged! Always use single-bracket .loc[row_mask, col] or .copy().
Try It Yourself in the Playground
Explore the exact mechanics of a DataFrame—row filtering with .loc, explicit copying, and immutable .assign() derived columns—right here in pure Python:
Click “Run Code” to execute this snippet right in your browser.
Real Pandas in the Browser (pandas Package)
Run real import pandas as pd .loc[] filtering and .assign() directly in your browser below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why does df.loc[0:2] return 3 rows when df has integer index labels 0, 1, 2, 3, whereas df.iloc[0:2] returns only 2 rows?
Quick Checkpoints
In Pandas, how should you filter rows where status == 'paid' and select only the customer and amount columns safely?
Why should you avoid chained assignment like df[df['score'] > 90]['grade'] = 'A'?
After filtering and dropping rows, your DataFrame's index has labels [0, 4, 9]. What does df.iloc[1] return?