Bird
Raised Fist0
Pandasdata~20 mins

Multiple conditions with & and | in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of Multiple Conditions
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of filtering DataFrame with multiple conditions
What is the output DataFrame after applying the filter with multiple conditions using & and | operators?
Pandas
import pandas as pd

data = {'Name': ['Anna', 'Bob', 'Charlie', 'David', 'Eva'],
        'Age': [23, 35, 45, 35, 23],
        'Score': [88, 92, 85, 70, 88]}
df = pd.DataFrame(data)

filtered = df[(df['Age'] > 30) & ((df['Score'] > 80) | (df['Name'] == 'David'))]
print(filtered)
A
    Name  Age  Score
3  David   35     70
B
    Name  Age  Score
1    Bob   35     92
2 Charlie   45     85
C
    Name  Age  Score
1    Bob   35     92
2 Charlie   45     85
3  David   35     70
D
Empty DataFrame
Columns: [Name, Age, Score]
Index: []
Attempts:
2 left
💡 Hint
Remember to use parentheses around each condition when combining with & and | in pandas.
❓ data_output
intermediate
1:30remaining
Count rows matching complex conditions
How many rows in the DataFrame satisfy the condition: (Age < 40) | (Score >= 90) and Name starts with 'A' or 'E'?
Pandas
import pandas as pd

data = {'Name': ['Anna', 'Bob', 'Charlie', 'David', 'Eva'],
        'Age': [23, 35, 45, 35, 23],
        'Score': [88, 92, 85, 70, 88]}
df = pd.DataFrame(data)

condition = ((df['Age'] < 40) | (df['Score'] >= 90)) & (df['Name'].str.startswith(('A','E')))
count = df[condition].shape[0]
print(count)
A3
B2
C1
D4
Attempts:
2 left
💡 Hint
Check which names start with A or E first, then apply the combined numeric conditions.
🔧 Debug
advanced
1:30remaining
Identify the error in filtering with multiple conditions
What error does the following code raise when filtering a DataFrame with multiple conditions using & and | without parentheses?
Pandas
import pandas as pd

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

filtered = df[df['A'] > 1 & df['B'] < 6]
print(filtered)
ATypeError: unsupported operand type(s) for &: 'int' and 'Series'
BSyntaxError: invalid syntax
CValueError: The truth value of a Series is ambiguous
DNo error, prints filtered DataFrame
Attempts:
2 left
💡 Hint
Operator precedence matters when combining conditions in pandas.
❓ visualization
advanced
2:30remaining
Visualize filtered data with multiple conditions
Which plot correctly shows the filtered data points where (Age >= 30) & (Score < 90) from the DataFrame?
Pandas
import pandas as pd
import matplotlib.pyplot as plt

data = {'Name': ['Anna', 'Bob', 'Charlie', 'David', 'Eva'],
        'Age': [23, 35, 45, 35, 23],
        'Score': [88, 92, 85, 70, 88]}
df = pd.DataFrame(data)

filtered = df[(df['Age'] >= 30) & (df['Score'] < 90)]

plt.scatter(filtered['Age'], filtered['Score'])
plt.xlabel('Age')
plt.ylabel('Score')
plt.title('Filtered Data Points')
plt.show()
AScatter plot with points at (23,88), (35,70), (45,85)
BScatter plot with points at (23,88), (35,92), (23,88)
CScatter plot with points at (35,92), (45,85), (23,88)
DScatter plot with points at (35,85), (45,85), (35,70)
Attempts:
2 left
💡 Hint
Check which rows satisfy Age >= 30 and Score < 90 before plotting.
🚀 Application
expert
3:00remaining
Apply multiple conditions to categorize data
Given a DataFrame with columns 'Temperature' and 'Humidity', which code correctly creates a new column 'Weather' with values 'Hot & Dry', 'Hot & Humid', 'Cold' based on these conditions? - 'Hot & Dry' if Temperature > 30 and Humidity < 50 - 'Hot & Humid' if Temperature > 30 and Humidity >= 50 - 'Cold' otherwise
Pandas
import pandas as pd

data = {'Temperature': [35, 40, 25, 32, 28], 'Humidity': [45, 55, 60, 40, 70]}
df = pd.DataFrame(data)

# Fill in the code below

A
df['Weather'] = 'Cold'
df.loc[(df['Temperature'] &gt; 30) &amp; (df['Humidity'] &lt; 50), 'Weather'] = 'Hot &amp; Dry'
df.loc[(df['Temperature'] &gt; 30) &amp; (df['Humidity'] &gt;= 50), 'Weather'] = 'Hot &amp; Humid'
print(df)
B
df['Weather'] = df.apply(lambda row: 'Hot &amp; Dry' if row['Temperature'] &gt; 30 and row['Humidity'] &lt; 50 else 'Hot &amp; Humid' if row['Temperature'] &gt; 30 and row['Humidity'] &gt;= 50 else 'Cold', axis=1)
print(df)
C
df['Weather'] = pd.cut(df['Temperature'], bins=[-float('inf'),30,float('inf')], labels=['Cold','Hot'])
df.loc[df['Humidity'] &lt; 50, 'Weather'] = 'Hot &amp; Dry'
df.loc[df['Humidity'] &gt;= 50, 'Weather'] = 'Hot &amp; Humid'
print(df)
D
df['Weather'] = ['Hot &amp; Dry' if (t &gt; 30 and h &lt; 50) else 'Hot &amp; Humid' if (t &gt; 30 and h &gt;= 50) else 'Cold' for t, h in zip(df['Temperature'], df['Humidity'])]
print(df)
Attempts:
2 left
💡 Hint
Use vectorized conditions with loc for better performance and clarity.

Practice

(1/5)
1. Which operator should you use in pandas to select rows where age is greater than 30 and salary is above 50000?
easy
A. Use and to combine the two conditions without parentheses.
B. Use | to combine the two conditions without parentheses.
C. Use & to combine the two conditions with parentheses around each.
D. Use or to combine the two conditions with parentheses.

Solution

  1. Step 1: Understand the condition type

    We want rows where both conditions are true, so this is an AND condition.
  2. Step 2: Choose the correct pandas operator

    In pandas, & is used for AND between conditions, and each condition must be in parentheses.
  3. Final Answer:

    Use & to combine the two conditions with parentheses around each. -> Option C
  4. Quick Check:

    AND condition = & with parentheses [OK]
Hint: Use & with parentheses for AND conditions in pandas [OK]
Common Mistakes:
  • Using 'and' instead of & causes errors.
  • Not wrapping each condition in parentheses.
  • Using | instead of & for AND conditions.
2. Which of the following is the correct syntax to filter a DataFrame df for rows where df['A'] > 10 or df['B'] < 5?
easy
A. df[(df['A'] > 10) | (df['B'] < 5)]
B. df[(df['A'] > 10) & (df['B'] < 5)]
C. df[df['A'] > 10 | df['B'] < 5]
D. df[df['A'] > 10 or df['B'] < 5]

Solution

  1. Step 1: Identify the condition type

    The question asks for rows where either condition is true, so this is an OR condition.
  2. Step 2: Use correct pandas syntax for OR

    In pandas, | is used for OR, and each condition must be wrapped in parentheses inside the DataFrame filter.
  3. Final Answer:

    df[(df['A'] > 10) | (df['B'] < 5)] -> Option A
  4. Quick Check:

    OR condition = | with parentheses [OK]
Hint: Use | with parentheses for OR conditions in pandas [OK]
Common Mistakes:
  • Using & instead of | for OR conditions.
  • Not wrapping conditions in parentheses.
  • Using Python 'or' instead of | causes errors.
3. Given the DataFrame df below:
import pandas as pd
df = pd.DataFrame({'age': [25, 40, 35, 28], 'salary': [40000, 60000, 50000, 45000]})
filtered = df[(df['age'] > 30) & (df['salary'] >= 50000)]
print(filtered)

What will be the output?
medium
A. Rows with age > 30 or salary >= 50000: rows 1, 2, and 3
B. Rows with age > 30 and salary >= 50000: rows 1 and 2
C. Rows with age > 30 and salary >= 50000: row 1 only
D. Empty DataFrame

Solution

  1. Step 1: Check each row against conditions

    Row 0: age=25 (no), salary=40000 (no)
    Row 1: age=40 (yes), salary=60000 (yes)
    Row 2: age=35 (yes), salary=50000 (yes)
    Row 3: age=28 (no), salary=45000 (no)
  2. Step 2: Select rows where both conditions are true

    Rows 1 and 2 satisfy both conditions.
  3. Final Answer:

    Rows with age > 30 and salary >= 50000: rows 1 and 2 -> Option B
  4. Quick Check:

    Both conditions true for rows 1 and 2 [OK]
Hint: Check each condition row-wise, then combine with & [OK]
Common Mistakes:
  • Confusing & with | and selecting wrong rows.
  • Ignoring parentheses causing syntax errors.
  • Misreading >= as > or vice versa.
4. What is wrong with this pandas filter code?
df[(df['score'] > 80) & df['age'] < 30]

Choose the best fix.
medium
A. Use 'and' instead of &.
B. Replace & with | to fix the syntax.
C. Remove parentheses around the first condition.
D. Add parentheses around the second condition: df[(df['score'] > 80) & (df['age'] < 30)]

Solution

  1. Step 1: Identify the syntax error

    The second condition df['age'] < 30 is not wrapped in parentheses, which is required when using &.
  2. Step 2: Correct the syntax by adding parentheses

    Wrap the second condition in parentheses to fix the error: df[(df['score'] > 80) & (df['age'] < 30)]
  3. Final Answer:

    Add parentheses around the second condition: df[(df['score'] > 80) & (df['age'] < 30)] -> Option D
  4. Quick Check:

    Each condition must be in parentheses with & [OK]
Hint: Wrap each condition in parentheses when using & or | [OK]
Common Mistakes:
  • Not using parentheses around all conditions.
  • Using 'and' instead of &.
  • Changing & to | without reason.
5. You have a DataFrame df with columns temperature and humidity. You want to select rows where temperature is between 20 and 30 inclusive, or humidity is below 40. Which of the following code snippets correctly applies these conditions?
hard
A. df[((df['temperature'] >= 20) & (df['temperature'] <= 30)) | (df['humidity'] < 40)]
B. df[(df['temperature'] >= 20) & df['temperature'] <= 30 | (df['humidity'] < 40)]
C. df[(df['temperature'] >= 20) | (df['temperature'] <= 30) & (df['humidity'] < 40)]
D. df[(df['temperature'] >= 20) & (df['humidity'] < 40) | (df['temperature'] <= 30)]

Solution

  1. Step 1: Understand the condition logic

    We want rows where temperature is between 20 and 30 (both conditions combined with AND), OR humidity is below 40.
  2. Step 2: Apply correct operator precedence with parentheses

    Use parentheses to group the temperature range conditions with & and then combine with | for humidity condition.
  3. Final Answer:

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

    Group AND conditions, then OR with other condition [OK]
Hint: Group AND conditions in parentheses before OR [OK]
Common Mistakes:
  • Missing parentheses causing wrong logic.
  • Mixing & and | without grouping.
  • Using | inside AND group incorrectly.
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