Bird
Raised Fist0
Pandasdata~20 mins

query() for fast filtering in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of query() with multiple conditions
What is the output DataFrame after running this code?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [5, 4, 3, 2, 1],
    'C': ['x', 'y', 'x', 'y', 'x']
})

result = df.query('A > 2 and B < 4')
print(result)
A
   A  B  C
2  3  3  x
3  4  2  y
B
   A  B  C
0  1  5  x
1  2  4  y
CEmpty DataFrame\nColumns: [A, B, C]\nIndex: []
D
   A  B  C
2  3  3  x
3  4  2  y
4  5  1  x
Attempts:
2 left
💡 Hint
Remember that query() filters rows where both conditions are true.
❓ data_output
intermediate
1:30remaining
Number of rows after query filtering
How many rows remain after applying this query filter?
Pandas
import pandas as pd

df = pd.DataFrame({
    'score': [10, 20, 30, 40, 50],
    'passed': [True, False, True, False, True]
})

filtered = df.query('score >= 30 and passed == True')
print(len(filtered))
A1
B2
C3
D0
Attempts:
2 left
💡 Hint
Check which rows have score >= 30 and passed is True.
🔧 Debug
advanced
1:30remaining
Identify the error in query() usage
What error does this code raise when run?
Pandas
import pandas as pd

df = pd.DataFrame({'x': [1, 2, 3]})

result = df.query('x => 2')
print(result)
ASyntaxError
BValueError
CKeyError
DNo error, outputs filtered DataFrame
Attempts:
2 left
💡 Hint
Check the comparison operator syntax inside the query string.
🚀 Application
advanced
2:00remaining
Using query() with variables
Given variable threshold = 3, which option correctly filters rows where column 'val' is greater than threshold using query()?
Pandas
import pandas as pd

df = pd.DataFrame({'val': [1, 2, 3, 4, 5]})
threshold = 3
Adf.query('val > $threshold')
Bdf.query('val > threshold')
Cdf.query('val > @threshold')
Ddf.query('val > {threshold}')
Attempts:
2 left
💡 Hint
Use @ to refer to Python variables inside query strings.
🧠 Conceptual
expert
2:00remaining
Why use query() over boolean indexing?
Which is the main advantage of using pandas query() method instead of boolean indexing for filtering DataFrames?
Aquery() is always faster than boolean indexing in all cases
Bquery() supports filtering on columns with spaces without any special syntax
Cquery() automatically modifies the original DataFrame without creating a copy
Dquery() allows filtering using a string expression which can be more readable and concise
Attempts:
2 left
💡 Hint
Think about code readability and expression style.

Practice

(1/5)
1. What is the main purpose of the query() method in pandas?
easy
A. To filter rows of a DataFrame using a readable string expression
B. To sort the DataFrame by column values
C. To merge two DataFrames based on a key column
D. To create a new DataFrame from scratch

Solution

  1. Step 1: Understand the purpose of query()

    The query() method is designed to filter rows in a DataFrame by using a string expression that specifies conditions on columns.
  2. Step 2: Compare with other DataFrame methods

    Sorting is done by sort_values(), merging by merge(), and creating new DataFrames is done by constructors, not query().
  3. Final Answer:

    To filter rows of a DataFrame using a readable string expression -> Option A
  4. Quick Check:

    query() filters rows [OK]
Hint: Remember: query() filters rows with string conditions [OK]
Common Mistakes:
  • Confusing query() with sorting or merging methods
  • Thinking query() creates new DataFrames
  • Assuming query() modifies columns
2. Which of the following is the correct syntax to filter rows where column age is greater than 30 using query()?
easy
A. df.query('age > "30"')
B. df.query(age > 30)
C. df.query('age > 30')
D. df.query('age => 30')

Solution

  1. Step 1: Check the correct string format for query()

    The condition must be passed as a string, so it should be inside quotes: 'age > 30'.
  2. Step 2: Validate the comparison operator and quotes

    Operator must be >, not =>. Also, 30 should be a number, not a string with quotes.
  3. Final Answer:

    df.query('age > 30') -> Option C
  4. Quick Check:

    Use string with correct operator [OK]
Hint: Put condition inside quotes with correct operators [OK]
Common Mistakes:
  • Omitting quotes around the condition string
  • Using wrong comparison operator => instead of >
  • Putting numbers inside quotes making them strings
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'name': ['Anna', 'Bob', 'Cara'], 'score': [85, 92, 78]})

What is the output of df.query('score >= 80')?
medium
A. Rows with names Anna and Bob only
B. Rows with names Bob and Cara only
C. Rows with names Anna and Cara only
D. All rows

Solution

  1. Step 1: Identify rows where score >= 80

    Scores are Anna:85, Bob:92, Cara:78. Only Anna and Bob have scores 80 or above.
  2. Step 2: Understand query() filters these rows

    The query returns rows where the condition is true, so rows for Anna and Bob are returned.
  3. Final Answer:

    Rows with names Anna and Bob only -> Option A
  4. Quick Check:

    score >= 80 filters Anna and Bob [OK]
Hint: Check numeric condition matches rows carefully [OK]
Common Mistakes:
  • Including rows that don't meet the condition
  • Confusing >= with > or <= operators
  • Assuming query returns all rows
4. What is wrong with this code snippet?
df.query('age > 25 and city == New York')
medium
A. The column names must be in quotes
B. The operator 'and' is not allowed in query()
C. The query() method cannot filter by multiple conditions
D. The string New York should be quoted inside the query string

Solution

  1. Step 1: Check string literals inside query()

    String values like city names must be quoted inside the query string, e.g., city == "New York".
  2. Step 2: Verify use of 'and' and column names

    The 'and' operator is allowed, and column names do not need quotes inside the query string.
  3. Final Answer:

    The string New York should be quoted inside the query string -> Option D
  4. Quick Check:

    Quote string values inside query() [OK]
Hint: Quote string values inside query() conditions [OK]
Common Mistakes:
  • Not quoting string literals in conditions
  • Thinking 'and' is invalid in query()
  • Quoting column names unnecessarily
5. You have a DataFrame df with columns temperature and humidity. You want to filter rows where temperature is above 20 and humidity is below 50. Which query() call correctly does this?
hard
A. df.query('temperature > 20 or humidity < 50')
B. df.query('temperature > 20 and humidity < 50')
C. df.query('temperature > 20 & humidity < 50')
D. df.query('temperature > 20 && humidity < 50')

Solution

  1. Step 1: Understand logical operators in query()

    Within query strings, use and and or for combining conditions, not & or &&.
  2. Step 2: Match the condition requirements

    The problem wants temperature > 20 and humidity < 50, so the correct operator is and.
  3. Final Answer:

    df.query('temperature > 20 and humidity < 50') -> Option B
  4. Quick Check:

    Use 'and' for multiple conditions in query() [OK]
Hint: Use 'and' not '&' to combine conditions in query() [OK]
Common Mistakes:
  • Using bitwise operators (&, &&) instead of 'and'
  • Using 'or' instead of 'and' when both conditions needed
  • Mixing Python operators outside query() syntax
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard