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
Up next · Lesson 12 of 42
Sorting Data
1 min read
11 of 42 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

