pandas loc, iloc and Filtering: Label vs Position, Masks, query
loc goes by label and includes the end of a slice; iloc goes by position and stops before it. Then filter rows with masks, isin, between and query, and change values with one loc instead of chained brackets.
What you will learn
- Pick rows, columns and cells with loc (by label) and iloc (by position)
- Explain why a loc slice includes the end and an iloc slice doesn't
- Filter rows with masks combined by &, | and ~, plus isin, between and query
- Change values with one loc and avoid the chained assignment trap
Before you start
- pandas Series and DataFrames
- NumPy boolean masks
You know how to build a DataFrame and grab a column. Now you'll reach any row, any column, or any single value, and keep only the rows that match a rule. You'll do this every day when you work with data.
Think about a row of lockers in a gym. Each door has a number painted on it, its label, and here they happen to run 5, 4, 3, 2, 1. Someone says "open door number three": you don't count, you look for that number. Someone else says "open the fourth locker from the left": you ignore the paint and count, and you land on door 2. Two ways to find a locker, and they can give different lockers. In pandas, loc goes by the label and iloc goes by the position.
loc picks by label
import pandas as pd
df = pd.DataFrame({
"Name": ["Alice", "Bob", "Carol", "Dev"],
"Age": [25, 30, 35, 28],
"Score": [88, 92, 76, 95],
}, index=["r1", "r2", "r3", "r4"])
print(df)
print(df.loc["r1", "Name"])
print(df.loc["r2"])
print(df.loc[:, "Score"])
print(df.loc["r1":"r3", "Name":"Age"])
Name Age Score
r1 Alice 25 88
r2 Bob 30 92
r3 Carol 35 76
r4 Dev 28 95
Alice
Name Bob
Age 30
Score 92
Name: r2, dtype: object
r1 88
r2 92
r3 76
r4 95
Name: Score, dtype: int64
Name Age
r1 Alice 25
r2 Bob 30
r3 Carol 35
loc always reads the same way: rows first, then columns. Where row r1 and column Name cross, you get Alice. Leave the column out and you get a whole row as a Series. A colon means all rows.
Look at the slice in the last line: r3 is included, and so is Age. That isn't how normal Python slices behave. With labels you name the last one you want, and that's the one you get.
iloc picks by position
print(df.iloc[0, 1])
print(df.iloc[-1])
print(df.iloc[0:2, 0:2])
print(df.iloc[:, 2])
25
Name Dev
Age 28
Score 95
Name: r4, dtype: object
Name Age
r1 Alice 25
r2 Bob 30
r1 88
r2 92
r3 76
r4 95
Name: Score, dtype: int64
Only numbers, starting at zero. -1 is the last row, just like a list. And an iloc slice stops before the end, exactly like a Python list, so 0:2 gives two rows. iloc doesn't care what the labels say; it only counts.
When the labels are numbers
s = pd.Series(
[10, 20, 30, 40, 50],
index=[5, 4, 3, 2, 1],
)
print(s)
print(s.loc[3])
print(s.iloc[3])
print(s.loc[4:2])
print(s.iloc[1:3])
5 10
4 20
3 30
2 40
1 50
dtype: int64
30
40
4 20
3 30
2 40
dtype: int64
4 20
3 30
dtype: int64
The slices differ too: loc[4:2] runs from label 4 to label 2 with the end included (three values), while iloc[1:3] stops before position 3 (two values).
Rows and columns from a list
rows = ["r1", "r3"]
cols = ["Name", "Score"]
print(df.loc[rows, cols])
print(df.iloc[[0, 2], [0, 2]])
Name Score
r1 Alice 88
r3 Carol 76
Name Score
r1 Alice 88
r3 Carol 76
When the rows you want aren't next to each other, a list does what a slice can't. Use loc when you know the names and iloc when you know the positions.
A label that isn't there
Out of habit you'll write df.loc[0, "Name"]. On this table the traceback ends with:
KeyError: 0
loc only looks at labels, and there's no label 0, only r1 to r4. Use the label with loc, or if you really mean a position, switch to iloc.
Filtering with a condition
Often you don't know which rows you want, only the rule, like "everyone older than 25". It works just like masks in NumPy.
mask = df["Age"] > 25
print(mask)
print(df[mask])
print(df.loc[mask, ["Name", "Age"]])
r1 False
r2 True
r3 True
r4 True
Name: Age, dtype: bool
Name Age Score
r2 Bob 30 92
r3 Carol 35 76
r4 Dev 28 95
Name Age
r2 Bob 30
r3 Carol 35
r4 Dev 28
A filter is two steps: first a column of True and False with the same labels, then keep the True rows. Inside loc, the mask picks the rows and the list picks the columns.
Combining conditions
older = df["Age"] > 25
high = df["Score"] >= 90
print(df[older & high])
print(df[older | high])
print(df[~older])
print(df[(df["Age"] > 25) & (df["Score"] >= 90)])
Name Age Score
r2 Bob 30 92
r4 Dev 28 95
Name Age Score
r2 Bob 30 92
r3 Carol 35 76
r4 Dev 28 95
Name Age Score
r1 Alice 25 88
Name Age Score
r2 Bob 30 92
r4 Dev 28 95
& means and, | means or, ~ means not. In one line, each condition needs its own round brackets. Named masks are easier to read when the line gets long.
When the filter breaks
print(df[df["Age"] > 25 and df["Score"] >= 90])
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or a.all().
The word and wants one True or False on each side, and each side is a whole column. You get the same error with & but no brackets, df["Age"] > 25 & df["Score"] >= 90, because & runs first and joins 25 with df["Score"]. When you see this message while filtering, use & and put brackets around each condition.
isin, between and query
print(df[df["Name"].isin(["Alice", "Carol"])])
print(df[df["Age"].between(25, 30)])
print(df[~df["Name"].isin(["Alice"])])
Name Age Score
r1 Alice 25 88
r3 Carol 35 76
Name Age Score
r1 Alice 25 88
r2 Bob 30 92
r4 Dev 28 95
Name Age Score
r2 Bob 30 92
r3 Carol 35 76
r4 Dev 28 95
isin asks "is this value in my list?" and between includes both ends: Alice at 25 and Bob at 30 are in. You can also write the filter as text:
print(df.query("Age > 25 and Score >= 90"))
limit = 90
print(df.query("Score >= @limit"))
print(df.query("Name in ['Alice', 'Dev']"))
Name Age Score
r2 Bob 30 92
r4 Dev 28 95
Name Age Score
r2 Bob 30 92
r4 Dev 28 95
Name Age Score
r1 Alice 25 88
r4 Dev 28 95
Inside a query string, column names go in without df or quotes, the word and is fine, and @ brings in a Python variable. Same rows; pick whichever reads better.
Changing values with loc
The loc you read with can also write. Put it on the left of the equals sign:
df.loc["r1", "Age"] = 26
df.loc[df["Score"] < 80, "Score"] = 80
df.loc[df["Score"] >= 90, "Grade"] = "A"
print(df)
Name Age Score Grade
r1 Alice 26 88 NaN
r2 Bob 30 92 A
r3 Carol 35 80 NaN
r4 Dev 28 95 A
One cell, a mask of rows, or even a new column. Rows that didn't match get NaN, how pandas marks a missing value. loc picks the cells, the equals sign changes them, and it changes the original table.
The chained assignment trap
df[df["Age"] > 25]["Score"] = 0
print(df)
Name Age Score
r1 Alice 25 88
r2 Bob 30 92
r3 Carol 35 76
r4 Dev 28 95
S06L03_Selection\chained_assign.py:9: ChainedAssignmentError: A value is being set on a copy of a DataFrame or Series through chained assignment.
Such chained assignment never works to update the original DataFrame or Series, because the intermediate object on which we are setting values always behaves as a copy (due to Copy-on-Write).
Try using '.loc[row_indexer, col_indexer] = value' instead, to perform the assignment in a single step.
See the documentation for a more detailed explanation: https://pandas.pydata.org/docs/dev/user_guide/migration.html#chained-assignment
df[df["Age"] > 25]["Score"] = 0
Two sets of brackets in a row. In pandas 3 the first brackets give a result that behaves like a copy, a photocopy of those rows. The zeros go onto the photocopy, and the photocopy is thrown away. There's no traceback; the program carries on as if it worked, and the only sign is that warning. Do it in one step:
df.loc[df["Age"] > 25, "Score"] = 0
print(df)
Name Age Score
r1 Alice 25 88
r2 Bob 30 0
r3 Carol 35 0
r4 Dev 28 0
If an old tutorial or an AI tool gives you the chained form, change it to one loc. (The same copy-on-write idea appeared in Series and DataFrames.)
Recap
| Tool | Goes by | Slice end |
|---|---|---|
df.loc[rows, cols] | Label | Included |
df.iloc[rows, cols] | Position from 0 | Excluded |
df[mask], df.loc[mask, cols] | True/False per row | |
& | ~ | And, or, not, with brackets | |
isin, between, query | Shorter filters | |
df.loc[mask, "col"] = value | Change the original in one step |
Try it yourself: in loc_assign.py, give everyone under 30 a Grade of B. Or ask an AI tool to write it, then read every line it gives you.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
