Bird
Raised Fist0
Pandasdata~20 mins

Selecting rows by condition in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of Selecting Rows by Condition
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of filtering rows with multiple conditions
What is the output of this code snippet that filters rows where age is greater than 30 and score is at least 80?
Pandas
import pandas as pd

data = {'name': ['Anna', 'Bob', 'Cara', 'Dan'], 'age': [25, 35, 40, 28], 'score': [88, 75, 90, 85]}
df = pd.DataFrame(data)

result = df[(df['age'] > 30) & (df['score'] >= 80)]
print(result)
A
Empty DataFrame
Columns: [name, age, score]
Index: []
B
   name  age  score
2  Cara   40     90
C
   name  age  score
0  Anna   25     88
3  Dan    28     85
D
   name  age  score
1  Bob    35     75
2  Cara   40     90
Attempts:
2 left
💡 Hint
Remember to use & for 'and' conditions and parentheses around each condition.
❓ data_output
intermediate
1:30remaining
Number of rows after filtering by string condition
Given this DataFrame, how many rows remain after selecting rows where the 'city' column contains the substring 'York'?
Pandas
import pandas as pd

data = {'name': ['Alice', 'Brian', 'Clara', 'David'], 'city': ['New York', 'Yorktown', 'Boston', 'Newark']}
df = pd.DataFrame(data)

filtered = df[df['city'].str.contains('York')]
print(len(filtered))
A2
B3
C0
D1
Attempts:
2 left
💡 Hint
Check which city names include the substring 'York'.
🔧 Debug
advanced
2:00remaining
Identify the error in filtering rows with OR condition
What error does this code produce when trying to filter rows where 'score' is less than 50 or 'age' is greater than 60?
Pandas
import pandas as pd

data = {'name': ['Eve', 'Frank', 'Grace'], 'age': [45, 65, 70], 'score': [55, 40, 30]}
df = pd.DataFrame(data)

result = df[df['score'] < 50 or df['age'] > 60]
print(result)
ASyntaxError
BEmpty DataFrame
CValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
DCorrect output with filtered rows
Attempts:
2 left
💡 Hint
Check how to combine multiple conditions on pandas Series.
❓ visualization
advanced
2:30remaining
Visualizing filtered data distribution
Which plot correctly shows the count of rows where 'category' is 'A' or 'B' from this DataFrame?
Pandas
import pandas as pd
import matplotlib.pyplot as plt

data = {'category': ['A', 'B', 'C', 'A', 'B', 'C', 'A'], 'value': [10, 20, 30, 40, 50, 60, 70]}
df = pd.DataFrame(data)

filtered = df[df['category'].isin(['A', 'B'])]
counts = filtered['category'].value_counts()

counts.plot(kind='bar')
plt.show()
ABar chart with two bars labeled 'A' and 'B' showing counts 3 and 2 respectively
BPie chart showing categories 'A', 'B', and 'C' with counts 3, 2, and 2
CLine plot showing values over index for all categories
DScatter plot of 'value' vs 'category' for all rows
Attempts:
2 left
💡 Hint
Check which categories are included after filtering and what value_counts returns.
🚀 Application
expert
3:00remaining
Selecting rows with complex condition and calculating mean
Given this DataFrame, what is the mean 'score' of rows where 'age' is between 20 and 40 (inclusive) and 'passed' is True?
Pandas
import pandas as pd

data = {'name': ['Ian', 'Jane', 'Kyle', 'Lara', 'Mona'],
        'age': [22, 35, 41, 28, 39],
        'score': [88, 92, 85, 79, 95],
        'passed': [True, False, True, True, False]}
df = pd.DataFrame(data)

filtered = df[(df['age'] >= 20) & (df['age'] <= 40) & (df['passed'])]
mean_score = filtered['score'].mean()
print(round(mean_score, 2))
A88.5
B81.0
C85.67
D83.5
Attempts:
2 left
💡 Hint
Filter rows carefully, then calculate the average of the 'score' column.

Practice

(1/5)
1. What does the expression df[df['age'] > 30] do in pandas?
easy
A. Deletes rows where the 'age' column is greater than 30
B. Selects columns where the 'age' value is greater than 30
C. Selects rows where the 'age' column is greater than 30
D. Sorts the DataFrame by the 'age' column

Solution

  1. Step 1: Understand the condition inside the brackets

    The condition df['age'] > 30 creates a True/False mask for each row based on the 'age' value.
  2. Step 2: Apply the condition to select rows

    Using df[condition] returns only rows where the condition is True, i.e., 'age' > 30.
  3. Final Answer:

    Selects rows where the 'age' column is greater than 30 -> Option C
  4. Quick Check:

    Condition filters rows [OK]
Hint: Use df[condition] to filter rows by True/False mask [OK]
Common Mistakes:
  • Thinking it selects columns instead of rows
  • Confusing filtering with sorting
  • Using parentheses incorrectly around conditions
2. Which of the following is the correct syntax to select rows where column 'score' equals 100?
easy
A. df[df.score = 100]
B. df[df['score'] = 100]
C. df[df['score'] === 100]
D. df[df['score'] == 100]

Solution

  1. Step 1: Identify correct equality operator in pandas

    In pandas, to compare values, use double equals ==, not single = or triple ===.
  2. Step 2: Check correct column access syntax

    Using df['score'] is correct and safe for all column names.
  3. Final Answer:

    df[df['score'] == 100] -> Option D
  4. Quick Check:

    Use == for comparison and brackets for column [OK]
Hint: Use df[df['col'] == value] with double equals for condition [OK]
Common Mistakes:
  • Using single = instead of == for comparison
  • Using triple === which is invalid in Python
  • Accessing columns without quotes when name has special chars
3. Given the DataFrame:
import pandas as pd
data = {'name': ['Ann', 'Bob', 'Cara', 'Dan'], 'age': [25, 35, 30, 40]}
df = pd.DataFrame(data)
What is the output of df[df['age'] >= 30]?
medium
A. Rows with names Bob, Cara, and Dan
B. Rows with names Ann and Bob
C. Rows with names Ann and Cara
D. Rows with names Dan only

Solution

  1. Step 1: Evaluate the condition df['age'] >= 30

    This condition is True for ages 35 (Bob), 30 (Cara), and 40 (Dan).
  2. Step 2: Select rows where condition is True

    Rows with names Bob, Cara, and Dan are returned.
  3. Final Answer:

    Rows with names Bob, Cara, and Dan -> Option A
  4. Quick Check:

    age >= 30 selects Bob, Cara, Dan [OK]
Hint: Check condition True rows, then list their names [OK]
Common Mistakes:
  • Including Ann who is 25 (less than 30)
  • Confusing >= with >
  • Misreading the DataFrame data
4. What is wrong with this code to select rows where 'score' is above 50?
df[df['score'] > 50 && df['age'] < 30]
medium
A. Using && instead of & for combining conditions
B. Missing parentheses around each condition
C. Using single & instead of &&
D. Using | instead of & for and condition

Solution

  1. Step 1: Check operator for combining conditions in pandas

    In pandas, use single ampersand & for 'and', not double ampersand &&.
  2. Step 2: Confirm correct syntax

    Correct syntax is df[(df['score'] > 50) & (df['age'] < 30)] with parentheses and single &.
  3. Final Answer:

    Using && instead of & for combining conditions -> Option A
  4. Quick Check:

    Use & not && for and in pandas [OK]
Hint: Use & for and, | for or, with parentheses [OK]
Common Mistakes:
  • Using && which causes syntax error
  • Not adding parentheses around each condition
  • Using | instead of & for and
5. You have a DataFrame df with columns 'city', 'temperature', and 'humidity'. How do you select rows where the city is 'Paris' and temperature is above 20 or humidity is below 30?
hard
A. df[(df['city'] == 'Paris') & (df['temperature'] > 20) | (df['humidity'] < 30)]
B. df[(df['city'] == 'Paris') & ((df['temperature'] > 20) | (df['humidity'] < 30))]
C. df[df['city'] == 'Paris' & df['temperature'] > 20 | df['humidity'] < 30]
D. df[df['city'] == 'Paris' and df['temperature'] > 20 or df['humidity'] < 30]

Solution

  1. Step 1: Understand operator precedence and grouping

    Logical AND (&) has higher precedence than OR (|), so parentheses are needed to group OR conditions correctly.
  2. Step 2: Write correct condition with parentheses

    We want city == 'Paris' AND (temperature > 20 OR humidity < 30), so use:
    df[(df['city'] == 'Paris') & ((df['temperature'] > 20) | (df['humidity'] < 30))]
  3. Final Answer:

    df[(df['city'] == 'Paris') & ((df['temperature'] > 20) | (df['humidity'] < 30))] -> Option B
  4. Quick Check:

    Group OR inside AND with parentheses [OK]
Hint: Use parentheses to group OR inside AND conditions [OK]
Common Mistakes:
  • Missing parentheses causing wrong logic
  • Using Python 'and'/'or' instead of & and |
  • Not using parentheses around each condition
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