0
0
Pandasdata~20 mins

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

Choose your learning style9 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.