Python
Pandas Library
Data Analysis
iloc
loc

How are iloc and loc different?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

loc and iloc are pandas indexers, but they are not interchangeable. loc is label-based, while iloc is position-based, and that difference affects which inputs are valid, how slices behave, and which rows you actually get back.

Use loc when labels matter

loc selects rows and columns by their labels. If your index contains dates, IDs, or custom names, loc is usually the most readable choice.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {"sales": [10, 20, 30, 40], "region": ["NA", "EU", "APAC", "LATAM"]},
5    index=["a", "b", "c", "d"]
6)
7
8print(df.loc["b"])
9print(df.loc["a":"c"])
10print(df.loc[:, ["sales"]])

The important rule is that label slices with loc are usually inclusive on both ends. That means "a":"c" returns rows a, b, and c.

Use iloc when position matters

iloc ignores labels and works with zero-based integer positions, which makes it behave more like normal Python indexing.

python
print(df.iloc[1])
print(df.iloc[0:3])
print(df.iloc[:, [0]])

Here, 0:3 excludes position 3, just like normal Python slices do. That is one of the biggest differences from loc.

iloc is a better choice when your code means "first row," "last three columns," or "row number five regardless of label."

Integer labels are where confusion starts

Problems often appear when the DataFrame index itself contains integers. In that case, loc[2] and iloc[2] can point to different rows.

python
1numbers = pd.DataFrame(
2    {"value": [100, 200, 300]},
3    index=[2, 4, 6]
4)
5
6print(numbers.loc[4])   # label 4
7print(numbers.iloc[1])  # second row by position

If the index labels happen to look like positions, it becomes easy to read code incorrectly. That is why many pandas bugs are not syntax problems. They are intent problems.

Filtering and assignment follow the same rule

The label-versus-position difference matters not only for reading data but also for modifying it.

python
1mask = df["sales"] >= 20
2print(df.loc[mask, ["sales"]])
3
4df.loc["b", "sales"] = 25
5df.iloc[0, 0] = 99
6print(df)

In the first assignment, loc updates the row whose label is "b". In the second assignment, iloc updates the first row and first column by physical position.

When you are cleaning data or patching a subset of rows, choosing the wrong indexer can silently write to the wrong location.

Pick the indexer that matches the meaning of the data

A good mental rule is:

  • use loc when the index is part of the meaning of the data
  • use iloc when you care about row order or offset

For example, if your index is a timestamp or customer ID, label-based selection is usually the safer expression of intent. If you are sampling the first ten rows during exploratory work, iloc is more direct.

This becomes even more important in notebooks. DataFrames change shape over time, and code that relied on a row staying at position 5 can break semantically even if it still runs.

Common Pitfalls

The most common mistake is expecting loc slices to behave like Python slices. They usually include the stop label.

Another common issue is using iloc on data where the index labels are meaningful identifiers. That often works by accident until the row order changes.

People also get confused by integer-labeled indexes and assume loc[0] means "first row." It only means "row whose label is 0."

Finally, avoid mixing label names and integer positions in the same thought process. Pick the access model that matches your intent and stay consistent.

Summary

  • 'loc is label-based and iloc is position-based.'
  • 'loc slices are usually inclusive, while iloc slices follow normal Python rules.'
  • Integer-looking labels can make the difference easy to miss.
  • The same rules apply to assignment, not just selection.
  • Choose the indexer that matches whether your data is organized by meaning or by position.

Course illustration
Course illustration

All Rights Reserved.