Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 7/ 160
01. Python & Data Wrangling

Indexing, Slicing & Filtering

Select rows/columns with loc/iloc, boolean masks, and query-style filters without copy bugs.

Beginnerloc/iloc · Boolean Masks3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Same selection, three styles

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).

Key takeaway: loc by label, iloc by position, masks with & | ~ in parentheses.

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().

The silent no-op

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.

Key takeaway: Assign with one .loc; copy explicitly when you want an independent subset.

How it works, step by step

Step 1 of 4
Plan

1. Decide how you'll select

Labels → loc, positions → iloc, conditions → boolean mask or query.

label · position · condition
Key numbers at this step
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 / or between Series
  • Relying on whether a slice is a view or a copy

Selection methods

.loc
Best for: Label-based selection and safe assignment

Strengths: Works with masks; same call reads and writes.

Watch out: Slice ends are inclusive, which surprises list users.

.iloc
Best for: Positional selection regardless of index

Strengths: List-like semantics; safe on any index.

Watch out: Breaks when row order changes.

query()
Best for: Readable multi-condition filters

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"] = 1 and 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?
Interview tip: Always demonstrate assignment with a single .loc. It's the one pattern that works under every pandas version and avoids the notorious copy warning.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Indexing, Slicing & Filtering with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Pandas Series & DataFrames
Next topic
Handling Missing Values