Data analysis with pandas · Lesson 5 of 15
Filtering rows with conditions
Keep only the rows you need with a condition, combine conditions with & and |, and use isin, between and str.contains for common filters.
Filtering means keeping the rows that match a rule: students who passed, sales above €100, cities in one country. In pandas it takes two steps that you write as one line: a condition, then brackets.
The examples use this table of students' marks:
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chloe", "Dev", "Eva", "Finn"],
"class": ["A", "B", "A", "B", "A", "B"],
"maths": [72, 85, 64, 90, 58, 77],
"art": [88, 60, 91, 70, 82, 65],
})
print(df)name class maths art 0 Ana A 72 88 1 Ben B 85 60 2 Chloe A 64 91 3 Dev B 90 70 4 Eva A 58 82 5 Finn B 77 65
One condition
df["maths"] >= 70 gives True or False for every row (a boolean mask). Put it inside df[...] and only the True rows stay. The index labels are kept, so you can see which rows passed.
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chloe", "Dev", "Eva", "Finn"],
"class": ["A", "B", "A", "B", "A", "B"],
"maths": [72, 85, 64, 90, 58, 77],
"art": [88, 60, 91, 70, 82, 65],
})
mask = df["maths"] >= 70
print(mask.tolist())
print(df[mask])
print(df[df["class"] == "A"])[True, True, False, True, False, True]
name class maths art
0 Ana A 72 88
1 Ben B 85 60
3 Dev B 90 70
5 Finn B 77 65
name class maths art
0 Ana A 72 88
2 Chloe A 64 91
4 Eva A 58 82Several conditions
Combine conditions with & (and), | (or) and ~ (not). Put each condition in brackets: & is applied before >=, so without brackets Python reads the line in the wrong order and raises an error. The words and/or do not work here.
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chloe", "Dev", "Eva", "Finn"],
"class": ["A", "B", "A", "B", "A", "B"],
"maths": [72, 85, 64, 90, 58, 77],
"art": [88, 60, 91, 70, 82, 65],
})
good_both = df[(df["maths"] >= 70) & (df["art"] >= 70)]
print(good_both)
either = df[(df["maths"] >= 85) | (df["art"] >= 85)]
print(either["name"].tolist())
print(df[~(df["class"] == "A")]["name"].tolist())name class maths art 0 Ana A 72 88 3 Dev B 90 70 ['Ana', 'Ben', 'Chloe', 'Dev'] ['Ben', 'Dev', 'Finn']
df[df["maths"] >= 70 and df["art"] >= 70] fails with a ValueError about the truth value of a Series being ambiguous. Use & and brackets.Handy filter helpers
isin([...]): the value is one of a list.between(a, b): from a to b, both ends included.str.contains("x")andstr.startswith("x"): text tests on a column.
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chloe", "Dev", "Eva", "Finn"],
"class": ["A", "B", "A", "B", "A", "B"],
"maths": [72, 85, 64, 90, 58, 77],
"art": [88, 60, 91, 70, 82, 65],
})
print(df[df["name"].isin(["Ben", "Eva"])])
print(df[df["maths"].between(60, 75)]["name"].tolist())
print(df[df["name"].str.startswith("C")]["name"].tolist())name class maths art 1 Ben B 85 60 4 Eva A 58 82 ['Ana', 'Chloe'] ['Chloe']
Filter, then pick columns
loc takes a mask for the rows and column names at the same time. Counting the rows that match is just len(), or sum() of the mask, because True counts as 1.
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chloe", "Dev", "Eva", "Finn"],
"class": ["A", "B", "A", "B", "A", "B"],
"maths": [72, 85, 64, 90, 58, 77],
"art": [88, 60, 91, 70, 82, 65],
})
passed = df.loc[df["maths"] >= 70, ["name", "maths"]]
print(passed)
print("Passed:", len(passed), "of", len(df))
print("Art above 80:", int((df["art"] > 80).sum()))name maths 0 Ana 72 1 Ben 85 3 Dev 90 5 Finn 77 Passed: 4 of 6 Art above 80: 3
✎ Exercise
Print the name and art columns of students in class B with an art mark of at least 65. Then print how many students scored below 70 in maths.
Hint: Join the two conditions with & and wrap each in brackets; sum() of a True/False Series counts the True values.
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chloe", "Dev", "Eva", "Finn"],
"class": ["A", "B", "A", "B", "A", "B"],
"maths": [72, 85, 64, 90, 58, 77],
"art": [88, 60, 91, 70, 82, 65],
})
# your code here
Expected output:
name art 3 Dev 70 5 Finn 65 Below 70 in maths: 2
Show a solution
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chloe", "Dev", "Eva", "Finn"],
"class": ["A", "B", "A", "B", "A", "B"],
"maths": [72, 85, 64, 90, 58, 77],
"art": [88, 60, 91, 70, 82, 65],
})
b_art = df.loc[(df["class"] == "B") & (df["art"] >= 65), ["name", "art"]]
print(b_art)
print("Below 70 in maths:", int((df["maths"] < 70).sum()))name art 3 Dev 70 5 Finn 65 Below 70 in maths: 2
Check yourself
1. Which line keeps rows where price is above 10 and stock is above 0?
Use &, and put each condition in its own brackets.
2. What does df["age"].between(18, 30) include?
between includes both ends by default.
3. How do you keep rows whose city is Rome or Paris?
isin checks whether each value is in the list.