Module 2 · Beginner · Selecting and filtering data

loc vs iloc in pandas, with examples

loc vs iloc in pandas explained: select rows and columns by label or by position, slicing rules, filtering with loc, setting values, and the common errors.

By theprogrammers team · · 5 min read

loc and iloc are the two ways to pick rows and columns from a pandas DataFrame at the same time. The difference is simple once you see it: loc uses labels (names), and iloc uses integer positions (0, 1, 2…). Mixing them up is one of the most common pandas mistakes, because with the default row numbers they often look identical, until they suddenly don't.

This lesson explains both with side-by-side examples, the slicing rule that trips everyone up, and how to filter and change values with loc.

The example data

We'll use a table of cities, with population in millions (rounded figures), and the city name as the row label (the index):

import pandas as pd

cities = pd.DataFrame({
    "state":      ["UP", "UP", "Maharashtra", "Karnataka", "Delhi"],
    "population": [3.2, 3.9, 7.4, 13.2, 21.8],
    "literacy":   [84.1, 82.5, 89.6, 88.7, 86.2],
}, index=["Kanpur", "Lucknow", "Pune", "Bengaluru", "Delhi"])

print(cities)
                 state  population  literacy
Kanpur              UP         3.2      84.1
Lucknow             UP         3.9      82.5
Pune       Maharashtra         7.4      89.6
Bengaluru    Karnataka        13.2      88.7
Delhi            Delhi        21.8      86.2

The syntax

Both use square brackets with rows first, then columns, separated by a comma:

df.loc[row labels, column labels]
df.iloc[row positions, column positions]

Leave out the columns part to get all columns.

Selecting one value

print(cities.loc["Pune", "literacy"])    # 89.6
print(cities.iloc[2, 2])                 # 89.6: row 2, column 2

Same value, two routes. With loc you say what you want; with iloc you say where it is.

Selecting rows

print(cities.loc["Kanpur"])        # one row, as a Series
print(cities.iloc[0])              # the same row, by position
print(cities.loc[["Pune", "Delhi"]])   # several rows: pass a list

iloc also takes negative positions: cities.iloc[-1] is the last row.

The slicing rule: loc includes the end

This is the big difference. A loc slice includes the end label; an iloc slice excludes the end position, like Python lists:

print(cities.loc["Kanpur":"Pune"])    # Kanpur, Lucknow AND Pune
print(cities.iloc[0:2])               # positions 0 and 1 only
               state  population  literacy
Kanpur            UP         3.2      84.1
Lucknow           UP         3.9      82.5
Pune     Maharashtra         7.4      89.6
        state  population  literacy
Kanpur     UP         3.2      84.1
Lucknow    UP         3.9      82.5

Why the difference? With labels, you can't easily name "the one after Pune", so pandas includes the label you wrote. Positions follow normal Python rules.

Rows and columns together

print(cities.loc["Lucknow":"Pune", ["state", "literacy"]])
print(cities.iloc[1:3, [0, 2]])    # the same cells by position
               state  literacy
Lucknow           UP      82.5
Pune     Maharashtra      89.6

And : means "everything" on either side: cities.loc[:, "population"] is the whole population column.

When the index is numbers, the trap appears

After loading a CSV, the index is usually 0, 1, 2… and loc and iloc seem the same. They aren't. Sort the data and watch:

df = cities.reset_index(names="city").sort_values("population", ascending=False)
print(df)
print(df.loc[0, "city"])     # label 0
print(df.iloc[0]["city"])    # first row now
        city        state  population  literacy
4      Delhi        Delhi        21.8      86.2
3  Bengaluru    Karnataka        13.2      88.7
2       Pune  Maharashtra         7.4      89.6
1    Lucknow           UP         3.9      82.5
0     Kanpur           UP         3.2      84.1
Kanpur
Delhi

loc[0] still finds the row labelled 0 (Kanpur), wherever it now sits. iloc[0] gives whatever is first (Delhi). Ask yourself each time: do I mean "this particular row", or "the row in this position"?

Filtering with loc

loc accepts a boolean condition for the rows, so you can filter and choose columns in one step. This is the cleanest way to filter in pandas:

print(cities.loc[cities["literacy"] > 85, ["state", "literacy"]])
                 state  literacy
Pune       Maharashtra      89.6
Bengaluru    Karnataka      88.7
Delhi            Delhi      86.2

iloc doesn't accept a pandas condition directly. More on conditions in filter rows in pandas.

Changing values with loc

Use loc to set values, especially for rows that match a condition:

cities.loc["Kanpur", "population"] = 3.3
cities.loc[cities["state"] == "UP", "region"] = "North"
print(cities)
                 state  population  literacy region
Kanpur              UP         3.3      84.1  North
Lucknow             UP         3.9      82.5  North
Pune       Maharashtra         7.4      89.6    NaN
Bengaluru    Karnataka        13.2      88.7    NaN
Delhi            Delhi        21.8      86.2    NaN

Assigning to a new column name creates it, and rows that didn't match get NaN.

Avoid "chained" assignment like cities[cities["state"] == "UP"]["region"] = "North". It may change a temporary copy instead of cities, and pandas warns with a SettingWithCopyWarning (in newer versions it simply doesn't change anything). One loc call with rows and columns together always works.

at and iat: fast single values

For a single cell, at (labels) and iat (positions) are faster versions of loc and iloc:

print(cities.at["Delhi", "literacy"])    # 86.2
print(cities.iat[4, 2])                  # 86.2

Quick reference

You wantlociloc
One valuedf.loc["Pune", "literacy"]df.iloc[2, 2]
One rowdf.loc["Pune"]df.iloc[2]
Several rowsdf.loc[["Pune", "Delhi"]]df.iloc[[2, 4]]
A slice of rowsdf.loc["Kanpur":"Pune"] (end included)df.iloc[0:3] (end excluded)
One columndf.loc[:, "state"]df.iloc[:, 0]
Filter rowsdf.loc[df["x"] > 5]not directly

Practice

  1. Get Bengaluru's population with loc, then with iloc.
Show the answer
print(cities.loc["Bengaluru", "population"])    # 13.2
print(cities.iloc[3, 1])                        # 13.2
  1. Get the last two rows and the first two columns using iloc.
Show the answer
print(cities.iloc[-2:, :2])
  1. Show the state and population of cities with a population above 5 million, using one loc call.
Show the answer
print(cities.loc[cities["population"] > 5, ["state", "population"]])

Interview questions

What is the difference between loc and iloc?

loc selects by index labels and column names; iloc selects by integer positions. loc slices include the end label, iloc slices exclude the end position, and only loc accepts boolean Series for filtering rows.

Why can df.loc[0] and df.iloc[0] give different rows?

loc[0] finds the row whose label is 0; iloc[0] takes the first row in the current order. After sorting, filtering or setting a different index, they no longer match.

What is SettingWithCopyWarning and how do you avoid it?

It warns that you may be assigning to a temporary copy, usually from chained indexing like df[cond]["col"] = x. Use a single df.loc[cond, "col"] = x, or call .copy() when you deliberately make a subset you'll modify.

What to learn next

  1. Write any condition you need in filter rows in pandas.
  2. Revisit select columns in pandas.