Indexing and Selecting Data (loc, iloc)
Why selection matters
Section titled “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
Section titled “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
Section titled “Selecting columns”print(df["age"]) # returns a Seriesprint(df[["name", "score"]])Selecting rows with loc (labels)
Section titled “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)
Section titled “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)
Section titled “Boolean 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
Section titled “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 |
Section titled “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
Section titled “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
Section titled “🧪 Try It Yourself”Exercise 1 – Select With loc
Section titled “Exercise 1 – Select With loc”Exercise 2 – Select With iloc
Section titled “Exercise 2 – Select With iloc”Exercise 3 – Rows + Columns Together
Section titled “Exercise 3 – Rows + Columns Together”Selection often needs a differently shaped index first — see Reindexing and Data Alignment for how pandas rearranges and aligns data by label.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading