Python for Data Analytics & AutomationLesson 19 of 41
Lesson 19 of 41

Data Selection, Indexing & Filtering: loc, iloc, Boolean Indexing & query()

Overview & Learning Objectives

Selecting specific rows and columns is the most frequent task in data manipulation. Pandas provides two distinct indexers: `.loc[]` (label-based indexing matching row and column names) and `.iloc[]` (integer position-based indexing from 0 to N-1). For dynamic string-based filtering, `.query()` offers clean SQL-like syntax that executes efficiently.

  • Extract rows and columns using label-based indexing `.loc[row_label, col_label]`.
  • Slice records positionally using integer-based indexing `.iloc[row_idx, col_idx]`.
  • Filter multi-condition records cleanly with boolean vectors (`df[(df["A"] > 0) & (df["B"] == "X")]`).
  • Write expressive, clean filter statements using the `.query()` method.

Industry Standard

Standard: Google and Airbnb Python engineering style guides forbid chained indexing (`df["col"][row] = x`) because it triggers the notorious `SettingWithCopyWarning`; always use `.loc[row, col] = x`.

Real-World Example: ScoopCraft Target Outlet Filtering

ScoopCraft filters transactions from high-volume Bengaluru and Mumbai dark stores where order total exceeds ₹500.

Order IDStore CityOrder Total (₹)Fulfillment Time (mins)Qualification Status
ORD_801Bengaluru₹750.0012 minsTarget Met (Included)
ORD_802Delhi₹850.0018 minsExcluded (City Delhi)
ORD_803Mumbai₹620.0014 minsTarget Met (Included)
ORD_804Bengaluru₹320.009 minsExcluded (Total < ₹500)

Syntax & Core Code Implementation

import pandas as pd

df = pd.DataFrame({
    "city": ["Bengaluru", "Delhi", "Mumbai", "Bengaluru"],
    "revenue": [750.0, 850.0, 620.0, 320.0],
    "prep_time": [12, 18, 14, 9]
}, index=["ORD_801", "ORD_802", "ORD_803", "ORD_804"])

# 1. .loc: Label-based indexing [rows, cols] (Endpoints INCLUDED)
top_stores = df.loc["ORD_801":"ORD_803", ["city", "revenue"]]

# 2. .iloc: Integer-position indexing [rows, cols] (Endpoints EXCLUDED)
first_two = df.iloc[0:2, 0:2]

# 3. Boolean vector filtering
filtered = df[(df["city"].isin(["Bengaluru", "Mumbai"])) & (df["revenue"] >= 500)]

# 4. Clean SQL-like .query() filtering
min_rev = 500
result = df.query("city in ['Bengaluru', 'Mumbai'] and revenue >= @min_rev")

Parameters & Arguments Breakdown

  • .loc[row_label, col_label]: Selects by label. Slicing with .loc is INCLUSIVE of both start and stop labels.
  • .iloc[row_pos, col_pos]: Selects by integer position (0-indexed). Slicing is EXCLUSIVE of stop index (standard Python slicing).
  • .isin(values): Returns boolean Series indicating whether each element in column matches any element in values sequence.
  • .query(expr): Filters DataFrame with a boolean query string. Reference local environment variables with `@var_name`.

Sample Walkthrough (Q&A)

Question: What is the critical slicing difference between `df.loc[0:3]` and `df.iloc[0:3]` if index contains integers 0, 1, 2, 3, 4?

Code Pattern: df.loc[0:3] vs df.iloc[0:3]

Result: `loc[0:3]` returns 4 rows (0, 1, 2, 3); `iloc[0:3]` returns 3 rows (positions 0, 1, 2).

Explanation: `.loc` slices by label and is INCLUSIVE of the endpoint. `.iloc` slices by integer position and is EXCLUSIVE of the endpoint.

Common Mistakes & Limitations

  • Chained assignment like `df[df["A"] > 5]["B"] = 10`, which triggers `SettingWithCopyWarning` and may fail to modify the original DataFrame.
  • Forgetting the `@` symbol when referencing external Python variables inside `.query("revenue > @min_revenue")`.

Keyboard Shortcuts (Jupyter & VS Code)

ActionWindowsMac
Select Specific Row by Labeldf.loc["ROW_ID"]df.loc["ROW_ID"]
Select Specific Row by Positiondf.iloc[0]df.iloc[0]

Pro Tips & Modern Best Practices

  • Use `.at[row, col]` and `.iat[row, col]` for single-cell scalar lookups; they are 3x faster than `.loc` and `.iloc` by bypassing Series overhead.
  • Use `.isin()` instead of chaining multiple `|` OR conditions.