We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Multiple Conditions

Real-world filtering rarely involves just one condition. Pandas lets you combine conditions using the logical operators & ("and") and | ("or").

AND Condition

Say I want to filter for basketball players averaging between 20 and 30 points per game:

solid_scorers = df[(df["ppg"] >= 20.0) & (df["ppg"] <= 30.0)]
print(solid_scorers)
#             player     team   ppg    status
# 0     Jayson Tatum  Celtics  26.9    active
# 13    Devin Booker     Suns  27.1    active
# 15    Jrue Holiday  Celtics  21.4   injured

Each condition must be wrapped in its own parentheses when combined: (condition_1) & (condition_2). Leaving them out causes a Python operator precedence error.

Don't Confuse Operators

In Pandas, always use & and | instead of and and or.

We can't use the regular Python logical operators because they work with single True/False values. When filtering a DataFrame, we're comparing entire Series at once.

OR Condition

Say we want the records for players at the extremes – either bench warmers (under 5 ppg) or superstars (over 35 ppg):

extreme_scorers = df[(df["ppg"] < 5) | (df["ppg"] > 35)]
print(extreme_scorers)
#               player       team   ppg  status
# 4        Joel Embiid      76ers  35.3  active
# 9   Payton Pritchard    Celtics   4.1  active
# 16       Luka Doncic  Mavericks  38.7  active

You can mix & and | in a single filter – just keep each piece wrapped in parentheses so the grouping is clear.

Assignment

SnackStack's support team knows a device needs a technician's attention when it's online and either a fridge running too warm or an oven running too cold.

Complete the find_devices_needing_attention function. It accepts a DataFrame of device readings and returns only the rows that need attention.

The DataFrame has device_id, device_type, temperature_celsius, and status columns.