Python lesson
Filtering with &
Only Lagos orders worth more than 50 are kept. Forgetting the brackets around each test is the most common mistake.
Try this lesson free →Example
Join two tests with &. Each test goes in its own brackets:
df[(df["Store"] == "Lagos") & (df["Revenue"] > 50)]Order Day Store Product Qty Revenue
0 O101 Mon Lagos Earbuds 2 70
7 O108 Fri Lagos Earbuds 3 105Key points
(test1) & (test2)Both must be true. Like AND in a spreadsheet.
BracketsWrap each test in its own ( ), or Python gets the order wrong.
& not andIn pandas, use &. The word and doesn't work on whole columns.
Put together: df[(df["Store"] == "Lagos") & (df["Revenue"] > 50)].
Practice
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 Abuja orders with a quantity of 4 or more.
df[(df["Store"] == "Abuja") & (df["Qty"] >= 4)]3. Show the Abuja orders worth more than 30.
df[(df["Store"] == "Abuja") & (df["Revenue"] > 30)]4. Show the Earbuds orders worth more than 100.
df[(df["Product"] == "Earbuds") & (df["Revenue"] > 100)]5. Show the Lagos orders with a quantity of 2 or more.
df[(df["Store"] == "Lagos") & (df["Qty"] >= 2)]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 →