~/learn/Pandas · Selecting rows

Filtering and sorting

Boolean masks, loc and sort_values.

7 min readlesson 2 of 13masklocsort_values

why this matters

Filtering rows is the pandas version of WHERE — the step behind nearly every analysis.

A comparison on a column produces a boolean Series. Passing it back into the frame keeps the rows where it is True.

python · editable
loading editor…

Combine conditions with & and | — each condition needs its own brackets. .isin() matches a list of values and ~ negates a mask.

python · editable
loading editor…

Use .loc for label-based selection of rows and columns at once, and sort_values to order the result.

python · editable
loading editor…

Brackets and &

Combine conditions with & and |, not and/or, and wrap each in brackets: df[(df.units > 2) & (df.country == "UK")].

key takeaways

  • df[mask] keeps rows where mask is True.
  • .loc[rows, cols] selects by label.
  • sort_values sorts rows.

check your understanding

Which keeps UK rows with more than 2 units?

free practice

Build confidence with a question you can solve without Pro.