🎓 A1Learner
🔍
0 of 50 lessons completed

Several Conditions at Once

Several conditions combine into one mask. The & sign means and, the | sign means or, and isin tests a list of values.

And: two conditions together

Only Tea is a Drink with more than 1 unit.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "units": [2, 1, 3, 5],
})
print(df[(df["category"] == "Drink") & (df["units"] > 1)])

Or: either condition

Mug is Home, and Pen has more than 2 units. Both rows pass.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "units": [2, 1, 3, 5],
})
print(df[(df["category"] == "Home") | (df["units"] > 2)])

isin tests a list

isin checks each product against the list Tea and Mug.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "units": [2, 1, 3, 5],
})
print(df[df["product"].isin(["Tea", "Mug"])])

Example

import io
import pandas as pd

SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
print(sales[(sales["category"] == "Drink") & (sales["units"] >= 2)])

Key points

  • Use & when every condition must be true.
  • Use | when any one condition may be true.
  • Wrap each condition in brackets, or Python reads the signs in the wrong order.
  • Use isin with a list to test many values at once.
  • A combined mask is still one Series of True and False.

In this example, the sales table is read from the CSV text. The mask combines two tests with &. A row must be a Drink and have 2 or more units. Three rows pass both tests.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which code keeps rows where the category is Drink or Home?