Python Central HubSign in

Data Analytics with Python / Phase 3: Data Manipulation with Pandas

Indexing and Selecting Data (loc, iloc)

Learn how to select rows and columns correctly using labels vs positions with loc/iloc, plus common filtering patterns.

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-based
  • iloc → position-based

Setup example DataFrame

Python
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

Python
print(df["age"])  # returns a Series
Python
print(df[["name", "score"]])

Selecting rows with loc (labels)

Python
print(df.loc["u2"])          # one row (Series)
print(df.loc[["u1", "u4"]]) # multiple rows (DataFrame)

Selecting rows + columns together:

Python
print(df.loc[["u1", "u3"], ["name", "score"]])

Selecting rows with iloc (positions)

Python
print(df.iloc[0])      # first row
print(df.iloc[0:2])    # first two rows
print(df.iloc[:, 0:2]) # first two cols

Boolean filtering (most common)

Python
filtered = df[df["city"] == "Delhi"]
print(filtered)

Combine conditions:

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

Safer assignment after filtering

When you filter and then assign, prefer .loc:

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

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.

🧪 Try It Yourself

Exercise 1 – Select With loc

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Select With iloc

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Rows + Columns Together

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Check your understanding

quizCheck yourself
  1. What is the difference between loc and iloc?

    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.

  2. With index labels u1 to u4, what does df.iloc[0:2] return?

    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.

  3. Which filter returns only Zoya from the sample data?

    Show answer

    A — df[(df["city"] == "Pune") & (df["score"] >= 90)] — Asha and Zoya live in Pune, but only Zoya scored 95 or more.

  4. Why does the lesson prefer df.loc[mask, "is_delhi"] = True for assignment after filtering?

    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.

Was this page helpful?

Let us know how we did