Filter rows with boolean masks: build a condition on columns, then pass it inside df[mask] or df.loc[mask]. Combine conditions with &, |, and ~—not Python and/or.
Single condition
import pandas as pd
df = pd.DataFrame({'price': [5, 15, 25], 'cat': ['A','B','A']})
cheap = df[df['price'] < 20]
print(cheap)
Multiple conditions
mask = (df['price'] >= 10) & (df['cat'] == 'A')
result = df.loc[mask]
print(result)
Useful helpers
df.query('price > 10 and cat == "A"')— readable for many columnsdf.isin({'col': [1, 2, 3]})— membership filterdf.between(left, right)— range filter on Seriesdf.nlargest(n, 'col')— top N rows by column
Important interview questions and answers
- Q: Why parentheses?
A: Operator precedence:&binds tighter than comparison—wrap each condition. - Q: query vs bracket?
A: query reads like SQL; brackets work everywhere and support complex masks.
Self-check
- Filter rows where price is between 10 and 30.
- Combine two boolean conditions with &.
Pitfall: Wrap each condition in parentheses when combining with & and |.
Interview prep
- & vs and?
Use & | ~ with parentheses for element-wise boolean arrays.
- query?
Readable string filter—alternative to bracket notation.