The query() Method
The query() method provides a SQL-like syntax for filtering DataFrames. It's often more readable than boolean indexing.
Basic Query Syntax
Write conditions as strings:
Loading Pandas Playground...
Comparison with Boolean Indexing
Compare readability:
Loading Pandas Playground...
Using Variables in Queries
Reference Python variables with @:
Loading Pandas Playground...
Complex Queries
Combine conditions with and, or, not:
Loading Pandas Playground...
Query with in and not in
Check membership in lists:
Loading Pandas Playground...
String Methods in Query
Use string methods with .str:
Loading Pandas Playground...
Exercise: Simple Query
Loading Exercise...
Exercise: Query with Variable
Loading Exercise...
Key Points
query()uses string expressions for filtering- More readable than boolean indexing
- Use
@variableto reference Python variables - Use
and,or,notinstead of&,|,~ - Use
inandnot infor membership checks - For string methods, stick with
.straccessor

