Skip to content

Indexing and Selecting Data (loc, iloc)

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-based
  • iloc → position-based
Sample 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)
One column
print(df["age"])  # returns a Series
Multiple columns
print(df[["name", "score"]])
loc by label
print(df.loc["u2"])          # one row (Series)
print(df.loc[["u1", "u4"]]) # multiple rows (DataFrame)

Selecting rows + columns together:

loc rows + cols
print(df.loc[["u1", "u3"], ["name", "score"]])
iloc by position
print(df.iloc[0])      # first row
print(df.iloc[0:2])    # first two rows
print(df.iloc[:, 0:2]) # first two cols
Filter rows
filtered = df[df["city"] == "Delhi"]
print(filtered)

Combine conditions:

Multiple conditions
filtered = df[(df["city"] == "Pune") & (df["score"] >= 90)]
print(filtered)

When you filter and then assign, prefer .loc:

Safe assignment with loc
df.loc[df["city"] == "Delhi", "is_delhi"] = True
 
df["is_delhi"] = df["is_delhi"].fillna(False)
print(df)

In Pandas boolean filters:

  • Use & for AND, | for OR
  • Always wrap sub-conditions in parentheses

This avoids operator precedence bugs.

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.

diagram loc vs iloc mermaid
loc addresses cells by label, iloc addresses the same cells by integer position.
sketch Label-based vs position-based selection p5.js
loc and iloc point at the exact same cell using two different coordinate systems.

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

pch.feedbackHeading

pch.feedbackSubheading