0
0
Pandasdata~5 mins

Multiple conditions with & and | in Pandas - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the & operator do in pandas when filtering data?
The & operator is used to combine multiple conditions with a logical AND, meaning both conditions must be true for the row to be selected.
Click to reveal answer
beginner
How do you combine multiple conditions with OR in pandas?
Use the | operator to combine conditions with a logical OR, so if any condition is true, the row is selected.
Click to reveal answer
intermediate
Why do you need to put each condition in parentheses when using & or | in pandas?
Parentheses ensure the correct order of operations because & and | have lower precedence than comparison operators like > or ==.
Click to reveal answer
beginner
Example: What does df[(df['age'] > 20) & (df['score'] < 50)] do?
It selects rows where the 'age' is greater than 20 AND the 'score' is less than 50.
Click to reveal answer
beginner
Can you use 'and' or 'or' instead of & and | for filtering pandas DataFrames?
No, 'and' and 'or' do not work element-wise on pandas Series. You must use & for AND and | for OR with parentheses.
Click to reveal answer
Which operator is used for element-wise AND in pandas filtering?
A|
Band
C&
D&&
What is the correct way to filter rows where 'age' > 30 OR 'score' < 70?
Adf[(df['age'] > 30) | (df['score'] < 70)]
Bdf[df['age'] > 30 | df['score'] < 70]
Cdf[df['age'] > 30 or df['score'] < 70]
Ddf[(df['age'] > 30) and (df['score'] < 70)]
Why must each condition be in parentheses when using & or | in pandas?
ABecause & and | have lower precedence than comparison operators
BTo improve code readability only
CIt is optional
DTo avoid syntax errors unrelated to precedence
What happens if you use 'and' instead of '&' in pandas filtering?
AIt works the same
BIt raises an error
CIt filters rows incorrectly
DIt converts to '&' automatically
Which of these filters rows where 'status' is 'active' AND 'score' is above 80?
Adf[df['status'] == 'active' and df['score'] > 80]
Bdf[df['status'] == 'active' & df['score'] > 80]
Cdf[(df['status'] == 'active') and (df['score'] > 80)]
Ddf[(df['status'] == 'active') & (df['score'] > 80)]
Explain how to filter a pandas DataFrame using multiple conditions with & and | operators.
Think about how to combine true/false checks for each row.
You got /4 concepts.
    Describe why parentheses are important when using multiple conditions in pandas filtering.
    Consider how Python reads expressions step-by-step.
    You got /3 concepts.