← Data analysis with Python

Several conditions at once

Combine conditions with & (and), | (or), ~ (not), and use isin.

Start this lesson

Real questions often have more than one condition: "coffee sales at the North store". In pandas you combine masks with & for and, | for or, and ~ for not. Each condition must sit in its own parentheses, because & and | are evaluated before comparisons like ==. To match any value from a list, .isin(["Mon", "Wed"]) is shorter than chaining several | conditions. And .between(10, 20) checks a range, including both ends.

import io
import pandas as pd

csv_text = """day,store,item,units,price
Mon,North,Coffee,30,3.5
Mon,North,Muffin,12,2.75
Mon,South,Coffee,22,3.5
Mon,South,Tea,9,3.0
Tue,North,Coffee,35,3.5
Tue,North,Tea,7,3.0
Tue,South,Coffee,18,3.5
Tue,South,Muffin,15,2.75
Wed,North,Muffin,10,2.75
Wed,South,Coffee,27,3.5
"""
sales = pd.read_csv(io.StringIO(csv_text))
north_coffee = sales[(sales["store"] == "North") & (sales["item"] == "Coffee")]
print(north_coffee)

not_coffee = sales[~(sales["item"] == "Coffee")]
early = sales[sales["day"].isin(["Mon", "Tue"])]
print(len(not_coffee), len(early))

north_coffee keeps 2 rows (Mon and Tue). ~ flips a mask, so not_coffee has the 5 non-coffee rows. isin keeps the 8 Monday and Tuesday rows.

Python’s words and, or, not do not work on whole columns. pandas gives "The truth value of a Series is ambiguous" if you try. Use &, |, ~ instead.