pandas
data manipulation
indexing
python programming
data analysis

Select Pandas rows based on list index

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Selecting rows by a list of indexes is a basic Pandas task, but it is also a common source of mistakes because Pandas supports both positional indexing and label-based indexing. The right method depends on whether your list contains row positions or actual index labels.

Use .iloc for Integer Positions

If your list means "give me the first, third, and fifth rows," use .iloc. It treats the values as zero-based positions regardless of the DataFrame's index labels.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "name": ["Alice", "Bob", "Charlie", "Dana", "Eve"],
6        "score": [91, 84, 88, 95, 79],
7    }
8)
9
10positions = [0, 2, 4]
11selected = df.iloc[positions]
12
13print(selected)

Output:

text
1      name  score
20    Alice     91
32  Charlie     88
44      Eve     79

.iloc also preserves the order of the list you pass in. If the list is [4, 0], the result will return Eve first and Alice second.

Use .loc for Index Labels

If your DataFrame has a custom index, row selection changes. In that case, use .loc when the list contains labels rather than positions.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "score": [91, 84, 88],
6        "city": ["Toronto", "Montreal", "Vancouver"],
7    },
8    index=["alice", "bob", "charlie"],
9)
10
11labels = ["charlie", "alice"]
12selected = df.loc[labels]
13
14print(selected)

Output:

text
         score       city
charlie     88  Vancouver
alice       91    Toronto

This is an important distinction: .loc does not mean "rows with these row numbers." It means "rows whose index labels match these values."

Selecting Safely When Indexes May Be Missing

Both .iloc and .loc raise an error when the requested rows do not exist. That is often desirable because it exposes bad assumptions early. If you want missing labels to produce NaN rows instead, use reindex.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "score": [91, 84, 88],
6    },
7    index=["alice", "bob", "charlie"],
8)
9
10wanted = ["alice", "dana"]
11selected = df.reindex(wanted)
12
13print(selected)

Output:

text
         score
alice     91.0
dana       NaN

That behavior is useful when you are aligning data from another source and want to preserve the requested order even if some rows are missing.

Filtering With a List of Conditions

Sometimes developers say "list index" when they actually have a boolean list, not a list of row numbers. That is a different operation. In that case, pass the boolean mask directly.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "name": ["Alice", "Bob", "Charlie", "Dana"],
6        "active": [True, False, True, False],
7    }
8)
9
10mask = [True, False, True, False]
11selected = df[mask]
12
13print(selected)

A boolean list must be the same length as the DataFrame. If it is not, Pandas raises an error.

Common Pitfalls

The most common mistake is confusing .loc and .iloc. If your DataFrame index happens to be integers, the bug can be subtle because both methods may run while meaning different things.

Another pitfall is assuming the DataFrame index is always the default 0, 1, 2 sequence. After filtering, sorting, or loading data from a file, the index may no longer match row positions. When you need position-based access after those operations, .iloc is usually the safer choice.

Out-of-range values also matter. With .iloc, requesting position 10 in a five-row DataFrame raises IndexError. With .loc, missing labels raise KeyError unless you use reindex.

Finally, watch out for duplicates. If your list contains repeated positions or labels, Pandas will repeat those rows in the result. That is sometimes exactly what you want, but it surprises people who expect automatic deduplication.

Summary

  • Use .iloc when your list contains row positions.
  • Use .loc when your list contains index labels.
  • Use reindex when you want missing labels to stay in the result instead of raising an error.
  • Boolean masks are a separate selection mechanism and must match the DataFrame length.
  • Always confirm whether your DataFrame index still matches row positions before selecting rows by a list.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.