query and where
query filters with a string expression, which reads cleanly. where keeps the shape and puts NaN where the condition fails.
Example
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': ['Ada', 'Bob', 'Cy', 'Di'], 'age': [30, 25, 35, 28], 'city': ['Lagos', 'Accra', 'Lagos', 'Nairobi'], 'score': [88.5, 92.0, 79.5, 85.0]})
print(df.query('age > 26 and city == "Lagos"')['name'].tolist())
min_score = 85
print(df.query('score >= @min_score')['name'].tolist())
print(df['score'].where(df['score'] > 85).tolist())Result
['Ada', 'Cy'] ['Ada', 'Bob', 'Di'] [88.5, 92.0, nan, nan]
Exercise
Filter by text.
df.("age > 30")
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.