Filtering with Masks

The same idea as numpy, applied to whole rows.

A condition on a column selects rows

The mask is one True or False per row, and putting it in the brackets keeps the rows it marked.

import pandas as pd

df = pd.DataFrame({"name": ["Ada", "Alan"], "score": [92, 79]})
print(df[df["score"] >= 85])

Combining conditions

Use & and | rather than and and or, and bracket each condition. The plain keywords ask for one True or False and a column cannot give them that.

import pandas as pd

df = pd.DataFrame({"score": [92, 79], "subject": ["maths", "maths"]})
print(df[(df["score"] >= 85) & (df["subject"] == "maths")].shape)

Exercise

Try It Yourself

Write passing_names(df, mark) returning a list of names whose score is at least mark, in the order they appear.

Press Run to see output

Check Your Understanding