Filtering Rows
Select rows that meet a condition — the pandas equivalent of SQL WHERE
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Filtering in pandas works just like NumPy boolean masking — create a boolean Series, use it to index rows.
# Single condition
df[df['age'] > 30]
df[df['city'] == 'New York']
# Multiple conditions — use & (and), | (or), ~ (not)
df[(df['age'] > 25) & (df['salary'] > 60000)]
df[(df['city'] == 'NY') | (df['city'] == 'LA')]
df[~df['name'].isna()] # rows where name is NOT nullString filtering with .str methods:
python df[df['name'].str.startswith('A')] df[df['email'].str.contains('@gmail')] df[df['name'].str.lower() == 'alice']
isin() — match a list of values:
python df[df['city'].isin(['New York', 'London', 'Tokyo'])]
query() — SQL-like string syntax:
python df.query('age > 30 and salary > 60000')
Examples
Filtering with multiple conditions
Always use & not and, | not or
import pandas as pd
df = pd.DataFrame({'name':['Alice','Bob','Carol','Dave'],'age':[25,35,28,42],'city':['NY','LA','NY','Chicago']})
# People in NY over 20
result = df[(df['city'] == 'NY') & (df['age'] > 20)]
print(result)
# Using isin
coasts = df[df['city'].isin(['NY','LA'])]
print(coasts)How well did you understand this?
Next in pandas
Handling Missing Values (NaN)