Editor

Fix the Bug: Boolean Filter

Intermediate · Fix the bug · from Pandas Indexing: loc, iloc, Boolean Indexing, and Selection

From the lesson: Pandas Indexing: loc, iloc, Boolean Indexing, and Selection

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.

Read the lesson

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())

More Pandas Indexing exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz