BBampaa

Lessons › Python

Python lesson

Filtering, two conditions

Only Lagos orders worth more than 50 are kept. Forgetting the brackets around each test is the most common mistake.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Join two tests with & when both must be true, or | when either is enough. Each test goes in its own brackets:

df[(df["Store"] == "Lagos") & (df["Revenue"] > 50)]

Output:

Order Day Store Product Qty Revenue
0 O101 Mon Lagos Earbuds 2 70
7 O108 Fri Lagos Earbuds 3 105

Key points

(test1) & (test2)Both must be true. Like AND.
(test1) | (test2)Either one is enough. Like OR.
BracketsWrap each test in its own ( ), or Python gets the order wrong.

Put together: df[(df["Product"] == "Earbuds") | (df["Product"] == "Charger")].

Practice

Try each one in your head first, then open the answer.

1. Build a line that keeps Lagos orders worth more than 50.
df[(df["Store"] == "Lagos") & (df["Revenue"] > 50)]
2. Build a line that keeps orders for Earbuds or Charger.
df[(df["Product"] == "Earbuds") | (df["Product"] == "Charger")]
3. Show the Lagos orders worth more than 50.
df[(df["Store"] == "Lagos") & (df["Revenue"] > 50)]
4. Show the orders from Monday or Friday.
df[(df["Day"] == "Mon") | (df["Day"] == "Fri")]
5. Show the Abuja orders with a quantity of 4 or more.
df[(df["Store"] == "Abuja") & (df["Qty"] >= 4)]

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed