Indexing, Slicing & Filtering
Select rows/columns with loc/iloc, boolean masks, and query-style filters without copy bugs.
In plain words
You can pick rows and columns by their names, by their position, or by asking a yes/no question about each row.
Think of it like…
Finding a book: .loc is "fetch the book labelled QA76.73" (by its label), .iloc is "the third book on the second shelf" (by position), and a boolean mask is "every book whose publication year is after 2020".
Where you’ve seen it
An analyst wants to flag high-value orders from the West region: df[(df["region"] == "West") & (df["amount"] > 5000)] selects them. To set a flag she writes df.loc[mask, "is_high_value"] = True rather than df[mask]["is_high_value"] = True, because the second form assigns into a temporary copy and the flag never appears in df.
Words you’ll hear
- .loc
- Label-based selection; slices include both ends.
- .iloc
- Position-based selection; slice end is excluded, like Python lists.
- Boolean mask
- A Series of True/False used to select rows; combine with
&,|,~. - Chained assignment
- Indexing twice then assigning, which may write to a copy; use one
.loc.
Visual diagram
Theory & deep dive
loc, iloc and boolean masks
df.loc[rows, cols] takes labels, label slices or boolean masks. With a date index, df.loc["2026-10":"2026-11"] slices inclusively. df.iloc[rows, cols] takes integer positions and behaves like list slicing (end excluded), which makes it safe on any index. Use df["col"] for one column and df[["a", "b"]] for several; plain df[mask] filters rows.
Combine conditions with & (and), | (or) and ~ (not), wrapping each comparison in parentheses because & binds tighter than >: df[(df.qty > 5) & (df.region == "West")]. Use .isin(values) for membership, .between(a, b) for ranges (inclusive by default) and .str.contains(...) for text. df.query("qty > 5 and region == 'West'") reads more naturally and can reference local variables with @name.
df.loc[df["qty"] > 5, ["order_id", "qty"]] (mask with columns), df.query("qty > 5")[["order_id", "qty"]] (query), and df.iloc[:10, :2] (first ten rows, first two columns by position).
Views, copies and safe assignment
Whether an indexing result is a view of the original or a copy depends on the operation, which is why the older SettingWithCopyWarning exists. Chained indexing such as df[df.qty > 5]["flag"] = 1 first creates an intermediate object and then assigns into it, so the original may stay unchanged. The reliable rule: to modify values, use a single .loc call, df.loc[df.qty > 5, "flag"] = 1; to keep a separate subset, call .copy().
Pandas 3.0 adopts copy-on-write by default: any result of indexing behaves as an independent copy, and chained assignment no longer modifies the original (it raises a warning or has no effect). The single .loc pattern works the same under both behaviours, so adopt it everywhere. When selecting a subset for later modification, always add .copy(): west = df[df.region == "West"].copy().
df[df["region"] == "West"]["discount"] = 0.1 appears to work but may not change df. df.loc[df["region"] == "West", "discount"] = 0.1 always does.
How it works, step by step
Step 1 of 41. Decide how you'll select
Labels → loc, positions → iloc, conditions → boolean mask or query.
- Ends
- loc inclusive, iloc exclusive
When to use it & trade-offs
What it is
Pandas gives you three ways to pick data. .loc selects by label (df.loc["2026-11-01", "sales"], with inclusive slice ends); .iloc selects by integer position (df.iloc[0:5, 1:3], end excluded); and boolean masks filter rows by a condition (df[df["sales"] > 100]). df.query("sales > 100 and region == 'West'") is a readable alternative. The most common bug in this area is assigning to a copy instead of the original frame.
Why it matters: Selecting and filtering are the most frequent operations in analysis, and two classic mistakes cause silent errors: chained indexing (df[df.a > 0]["b"] = 1) that modifies a temporary copy, and mixing up loc and iloc semantics on a non-default index. Getting these right makes code both correct and readable, and interviewers use them as a quick pandas-fluency test.
When to reach for it
- Filtering rows by conditions
- Selecting columns for modelling
- Setting flags and fixing values for a subset
When to avoid or be careful
- Chained indexing when assigning
and/orbetween Series- Relying on whether a slice is a view or a copy
Selection methods
Strengths: Works with masks; same call reads and writes.
Watch out: Slice ends are inclusive, which surprises list users.
Strengths: List-like semantics; safe on any index.
Watch out: Breaks when row order changes.
Strengths: Concise; supports @variable.
Watch out: String-based, so editors can't check it; limited expressions.
Interview signals & numbers to know
When this topic comes up
- “loc vs iloc?”
- “SettingWithCopyWarning”
- “Filter rows where two conditions hold”
- Boolean masks
- Copy semantics
Benchmarks & rules of thumb
- inclusive / exclusive
- loc vs iloc slice ends
- & | ~
- element-wise logic operators
- pandas 3.0
- copy-on-write by default
Common mistakes & follow-ups
Common interview mistakes
- Writing
df[df.a > 0]["b"] = 1and finding the original unchanged. - Forgetting parentheses:
df.qty > 5 & df.region == "West"raises an error or gives wrong results. - Using iloc after sorting and assuming positions still match the original rows.
Likely interviewer follow-ups
- What's the difference between loc and iloc?
- How do you safely update a subset of rows?
- Why does chained assignment fail?
.loc. It's the one pattern that works under every pandas version and avoids the notorious copy warning.Knowledge check
Put it into practice
Practice related interview Q&A
Apply Indexing, Slicing & Filtering with data science interview Q&A and hands-on practice.