Skip to main content
Editor

Pandas Indexing: loc, iloc, Boolean Indexing, and Selection

Intermediate25 min6 exercises90 XP
0/6 exercises

You have a DataFrame with thousands of rows. You need row 42. You need every customer from Texas. You need the salary in the third row, second column. Pandas gives you three different ways to grab exactly the data you want - and confusing them is one of the most common beginner mistakes.

In this tutorial, you'll learn the difference between label-based indexing (loc), position-based indexing (iloc), and boolean indexing (filtering with conditions). By the end, you'll always know which tool to reach for.

What Is loc? (Label-Based Indexing)

loc selects data by label - the names of your rows and columns. Think of it like looking up a word in a dictionary by its key, not by its page number.

loc selects by label
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'age': [28, 34, 22, 45],
'city': ['NYC', 'LA', 'NYC', 'Chicago']
}, index=['a', 'b', 'c', 'd'])
# Select row with label 'b'
print(df.loc['b'])
print()
# Select rows 'a' through 'c', columns 'name' and 'age'
print(df.loc['a':'c', ['name', 'age']])
Output
name    Bob
age      34
city     LA
Name: b, dtype: object

      name  age
a    Alice   28
b      Bob   34
c  Charlie   22

What Is iloc? (Position-Based Indexing)

iloc selects data by integer position - like indexing a list. It doesn't care about labels. Row 0 is the first row, row 1 is the second, and so on.

iloc selects by position
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'age': [28, 34, 22, 45],
'city': ['NYC', 'LA', 'NYC', 'Chicago']
})
# First row
print(df.iloc[0])
print()
# Rows 0-1, columns 0-1
print(df.iloc[0:2, 0:2])
Output
name    Alice
age        28
city      NYC
Name: 0, dtype: object

    name  age
0  Alice   28
1    Bob   34
loc: by label (inclusive)
df.loc[0:2]    # rows with LABELS 0, 1, 2
# Returns 3 rows
iloc: by position (exclusive)
df.iloc[0:2]   # rows at POSITIONS 0, 1
# Returns 2 rows

What Are .at and .iat? (Single-Value Access)

If you only need a single value, use .at (by label) or .iat (by position). They're faster than loc/iloc for scalar access because they skip the overhead of returning a Series or DataFrame.

.at and .iat for scalar access
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'score': [95, 87, 92]
})
# .at - label-based single value
print(df.at[1, 'name']) # 'Bob'
# .iat - position-based single value
print(df.iat[2, 1]) # 92
Output
Bob
92

How Does Boolean Indexing Work?

Boolean indexing is how you filter rows based on a condition. You write a condition that produces True/False for each row, then pass it into the brackets. Only the True rows survive.

Filtering rows with a condition
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'age': [28, 34, 22, 45],
'city': ['NYC', 'LA', 'NYC', 'Chicago']
})
# Filter: age > 30
older = df[df['age'] > 30]
print(older[['name', 'age']].values.tolist())
Output
[['Bob', 34], ['Diana', 45]]

You can combine multiple conditions using & (and), | (or), and ~ (not). Each condition must be wrapped in parentheses.

Combining conditions with & and |
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'age': [28, 34, 22, 45],
'city': ['NYC', 'LA', 'NYC', 'Chicago']
})
# Combine conditions: age > 25 AND city == 'NYC'
result = df[(df['age'] > 25) & (df['city'] == 'NYC')]
print(result['name'].tolist())
Output
['Alice']

Can You Filter with .query()?

The .query() method lets you write filter conditions as a string. It's more readable for complex filters and avoids the bracket-and-ampersand clutter.

.query() for readable filters
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'age': [28, 34, 22, 45],
'salary': [70000, 85000, 52000, 120000]
})
# query() reads like plain English
result = df.query('age > 25 and salary > 60000')
print(result['name'].tolist())
Output
['Alice', 'Bob', 'Diana']

You can also reference external variables in .query() by prefixing them with @:

Using variables in .query()
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'salary': [70000, 85000, 52000]
})
min_salary = 60000
result = df.query('salary >= @min_salary')
print(result['name'].tolist())
Output
['Alice', 'Bob']

How Do You Update Values in a DataFrame?

You can use loc or at to set values too. This is how you update specific cells or entire columns based on conditions.

Updating values with loc and at
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'score': [85, 60, 92]
})
# Set a single value
df.at[1, 'score'] = 75
# Set values based on a condition
df.loc[df['score'] >= 90, 'grade'] = 'A'
df.loc[df['score'] < 90, 'grade'] = 'B'
print(df[['name', 'score', 'grade']].values.tolist())
Output
[['Alice', 85, 'B'], ['Bob', 75, 'B'], ['Charlie', 92, 'A']]

How Do You Filter for Multiple Values?

When you want to check if a column value is one of several options, use .isin(). It's cleaner than chaining multiple == conditions with |.

Verbose: chaining OR conditions
mask = (df['city'] == 'NYC') | (df['city'] == 'LA') | (df['city'] == 'Chicago')
result = df[mask]
Clean: using isin()
result = df[df['city'].isin(['NYC', 'LA', 'Chicago'])]
Filtering with isin()
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'city': ['NYC', 'LA', 'Boston', 'Chicago']
})
# Filter for people in NYC or Chicago
result = df[df['city'].isin(['NYC', 'Chicago'])]
print(result['name'].tolist())
Output
['Alice', 'Diana']

Quick Reference: When to Use What

Choosing the right indexer is straightforward once you ask yourself two questions:

  • Do I know the label or the position? Use loc for labels, iloc for positions.
  • Do I need one value or multiple? Use .at/.iat for a single cell (faster), loc/iloc for slices.
  • Am I filtering by a condition? Use boolean indexing or .query().
  • Am I checking membership in a list? Use .isin().

  • Practice Exercises

    Select with loc
    Write Code

    Given the DataFrame below with a custom index, use loc to select the row with label 'b' and print the 'name' value from that row.

    import pandas as pd
    df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [28, 34, 22]
    }, index=['a', 'b', 'c'])
    # Use loc to get Bob's name
    Select with iloc
    Write Code

    Use iloc to select the last two rows of the DataFrame and print their names as a list using .tolist().

    import pandas as pd
    df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
    'age': [28, 34, 22, 45]
    })
    # Select last 2 rows, get the 'name' column as a list
    Filter with Boolean Indexing
    Write Code

    Filter the DataFrame to find all employees with a salary greater than 70000. Print the names of matching employees as a list.

    import pandas as pd
    df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
    'salary': [70000, 85000, 52000, 120000]
    })
    # Filter for salary > 70000 and print names
    Multiple Conditions
    Write Code

    Filter the DataFrame to find people who are older than 25 AND live in NYC. Print their names as a list.

    import pandas as pd
    df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'age': [28, 34, 22, 45, 30],
    'city': ['NYC', 'LA', 'NYC', 'Chicago', 'NYC']
    })
    # Filter: age > 25 AND city == 'NYC'
    Fix the Bug: Boolean Filter
    Fix the Bug

    This code tries to filter rows where age is greater than 25 OR city is LA, but it raises an error. Fix the code so it prints the correct names as a list.

    import pandas as pd
    df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [28, 34, 22],
    'city': ['NYC', 'LA', 'NYC']
    })
    # Bug: this raises an error
    result = df[df['age'] > 25 or df['city'] == 'LA']
    print(result['name'].tolist())
    Update Values with loc
    Write Code

    Use loc to set the 'status' column to 'pass' for all rows where score >= 70, and 'fail' for rows where score < 70. Print the status column as a list.

    import pandas as pd
    df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie'],
    'score': [85, 60, 72]
    })
    # Set status based on score

    Harder problems

    More problems on this topic: Working with data

    Related Tutorials

    Was this tutorial helpful?