Skip to the workspace
Pebellslearn by building
pandas Series and DataFrames  ›  Lesson

Filtering and Querying

Filtering & Querying 14 minA condition on a column produces a boolean Series, and placing it in brackets or writing it in query keeps only the rows where it is True.

python data analysis / Filtering and Querying

Explore each scene at your own pace.

01 · The rule

The rule

Filtering and Querying

The Delhi manager asks: "Which of my sales were science books?" You do not want to scan eight rows by eye, and certainly not eighty thousand. Filtering keeps only the rows that answer yes to a question.

The rule

Build a True/False column, then keep the True rows.

A comparison on a column gives a boolean Series, one True or False per row:

sales["branch"] == "Delhi"
# 0 False, 1 True, 2 False, 3 False, 4 True, 5 False, 6 False, 7 True

Put that Series inside the brackets and pandas keeps the rows marked True:

delhi = sales[sales["branch"] == "Delhi"]      # rows 1, 4, 7

Combine conditions with & (and), | (or) and ~ (not), wrapping each condition in parentheses:

sales[(sales["branch"] == "Delhi") & (sales["genre"] == "science")]   # rows 1 and 7
sales[~(sales["genre"] == "comics")]                                  # everything except comics

Two helpers save typing:

sales[sales["branch"].isin(["Pune", "Chennai"])]   # branch is any of these
sales[sales["copies"].between(2, 4)]               # 2 to 4, ends included

.query() lets you write the same condition as a readable string, with plain and/or:

sales.query("branch == 'Delhi' and genre == 'science'")
sales.query("copies > 3")

To filter rows and choose columns at once, use loc:

sales.loc[sales["copies"] > 3, ["branch", "copies"]]
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.