Why selection matters
Most Pandas bugs come from:
- Selecting the wrong rows
- Accidentally getting a copy instead of a view
- Confusing label-based vs position-based indexing
Pandas provides two primary tools:
loc→ label-basediloc→ position-based
Setup example DataFrame
import pandas as pd
df = pd.DataFrame(
{
"name": ["Asha", "Ravi", "Meera", "Zoya"],
"age": [23, 28, 26, 31],
"city": ["Pune", "Delhi", "Delhi", "Pune"],
"score": [88, 91, 77, 95],
},
index=["u1", "u2", "u3", "u4"],
)
print(df)Selecting columns
print(df["age"]) # returns a Seriesprint(df[["name", "score"]])Selecting rows with loc (labels)
print(df.loc["u2"]) # one row (Series)
print(df.loc[["u1", "u4"]]) # multiple rows (DataFrame)Selecting rows + columns together:
print(df.loc[["u1", "u3"], ["name", "score"]])Selecting rows with iloc (positions)
print(df.iloc[0]) # first row
print(df.iloc[0:2]) # first two rows
print(df.iloc[:, 0:2]) # first two colsBoolean filtering (most common)
filtered = df[df["city"] == "Delhi"]
print(filtered)Combine conditions:
filtered = df[(df["city"] == "Pune") & (df["score"] >= 90)]
print(filtered)Safer assignment after filtering
When you filter and then assign, prefer .loc:
df.loc[df["city"] == "Delhi", "is_delhi"] = True
df["is_delhi"] = df["is_delhi"].fillna(False)
print(df)Note on & and |
In Pandas boolean filters:
- Use
&for AND,|for OR - Always wrap sub-conditions in parentheses
This avoids operator precedence bugs.
Visualize it
loc reads coordinates as labels ("row u2, column age"); iloc reads them as
positions ("row 1, column 1") — same grid, two different ways to point at a cell.
flowchart LR DF["DataFrame grid"] --> L["df.loc['u2', 'age'] (by label)"] DF --> I["df.iloc[1, 1] (by position)"] L --> V["Same cell"] I --> V
🧪 Try It Yourself
Exercise 1 – Select With loc
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 – Select With iloc
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 – Rows + Columns Together
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Check your understanding
What is the difference between loc and iloc?
df.loc["u2"] uses the row label, while df.iloc[1] uses the position.
Show answer
A — loc is label-based and iloc is position-based — df.loc["u2"] uses the row label, while df.iloc[1] uses the position.
With index labels u1 to u4, what does df.iloc[0:2] return?
iloc slices by position and excludes the stop, so positions 0 and 1 give the first two rows.
Show answer
A — Rows u1 and u2 — iloc slices by position and excludes the stop, so positions 0 and 1 give the first two rows.
Which filter returns only Zoya from the sample data?
Asha and Zoya live in Pune, but only Zoya scored 95 or more.
Show answer
A — df[(df["city"] == "Pune") & (df["score"] >= 90)] — Asha and Zoya live in Pune, but only Zoya scored 95 or more.
Why does the lesson prefer df.loc[mask, "is_delhi"] = True for assignment after filtering?
Assigning through loc with a mask and a column name writes into the original DataFrame.
Show answer
A — It is the safer way to assign and avoids copy-versus-view surprises — Assigning through loc with a mask and a column name writes into the original DataFrame.
Next
Selection often needs a differently shaped index first — see Reindexing and Data Alignment for how pandas rearranges and aligns data by label.