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.

6 min readUpdated 2026-11-30
In This Lesson
  • 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

Pandas DataFrame Anatomy: Index, Columns, axis=0 & axis=1
↓ axis=0 (down rows)→ axis=1 (across columns)
Indexstudenttrackhours
0MayaData14
1LiamBackend9

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 of Series objects 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:

python
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 columns
Always Run df.info() First

df.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 styleLabel-based (row index names & column names)Position-based (0-based integer offsets)
Boolean masksYes (df.loc[df["hours"] > 10, ["student"]])Not directly on Series masks
Slice end behaviorInclusive (df.loc[0:2] includes label 2)Exclusive (df.iloc[0:2] stops before 2)
Typical useBusiness filters, named column subsets, updatesFirst/last N rows (df.iloc[:5, :3])

Line-by-Line Walkthrough of Safe Filtering

python
# 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:

  1. df["completed"] is already a boolean Series ([True, False, True]).
  2. (df["track"] == "Data") produces [True, False, True].
  3. Bitwise & combines them element-wise ([True, False, True]).
  4. .loc[mask, ["student", "hours"]] keeps only True rows 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:

python
# 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,
)
Why Chained Assignment Breaks Silently

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:

Python 3Try It Live: Tabular DataFrame Mechanics
Output

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:

Python 3Try Real Pandas Live: DataFrame, .loc[] & .assign()
Output

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

Check Your Understanding

In Pandas, how should you filter rows where status == 'paid' and select only the customer and amount columns safely?

Check Your Understanding

Why should you avoid chained assignment like df[df['score'] > 90]['grade'] = 'A'?

Check Your Understanding

After filtering and dropping rows, your DataFrame's index has labels [0, 4, 9]. What does df.iloc[1] return?