Some other interesting usages in the documentation.
Reuseable
A use case for query() is when you have a collection of DataFrame
objects that have a subset of column names (or index levels/names) in
common. You can pass the same query to both frames without having to
specify which frame you’re interested in querying -- (Source)
Example:
dfA = pd.DataFrame([[1,2,3], [4,5,6]], columns=["X", "Y", "Z"])
dfB = pd.DataFrame([[1,3,3], [4,1,6]], columns=["X", "Y", "Z"])
q = "(X > 3) & (Y < 10)"
print(dfA.query(q))
print(dfB.query(q))
X Y Z
1 4 5 6
X Y Z
1 4 1 6
More flexible syntax
df.query('a < b and b < c') # understand a bit more English
Support in operator and not in (alternative to isin)
df.query('a in [3, 4, 5]') # select rows whose value of column a is in [2, 3, 4]
Special usage of == and != (similar to in/not in)
df.query('a == [1, 3, 5]') # select whose value of column a is in [1, 3, 5]
# equivalent to df.query('a in [1, 3, 5]')