Sub topic 6
Selecting, filtering and sorting
This chapter maps the pandas idioms for choosing columns, choosing rows and ordering rows to their Polars equivalents. It assumes you know pandas boolean masks, loc and iloc, and sort_values. It also assumes you have read the earlier chapters on expressions and contexts. Every example uses this small frame:
import polars as pl
df = pl.DataFrame(
{
"region": ["north", "south", "north", "east", "south"],
"status": ["paid", "paid", "open", "open", "paid"],
"price": [10.0, 20.0, None, 5.0, 8.0],
"qty": [3, 5, 2, 0, 4],
}
)Selecting columns
pandas selects columns by indexing the frame. Polars uses the select context, which takes column names or expressions and returns a new frame.
# pandas
sub = pdf[["region", "price"]]
# Polars
sub = df.select("region", "price")
sub = df.select(pl.col("region", "price"))
sub = df.drop("status", "qty")select returns only the columns you name. A computed column inside select therefore replaces the rest of the frame. If you want to keep every column and add one, use with_columns instead (see the chapter on creating columns).
only_total = df.select((pl.col("price") * pl.col("qty")).alias("total"))
everything_plus = df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))Selecting by pattern or dtype
pandas uses select_dtypes or filter(like=...). Polars has pl.col with regular expressions and the polars.selectors module.
import polars.selectors as cs
numbers = df.select(cs.numeric())
text = df.select(cs.string())
no_text = df.select(pl.exclude("region", "status"))
by_regex = df.select(pl.col("^(price|qty)$"))A name that starts with ^ and ends with $ is read as a regular expression. Selectors are easier to read and can be combined with |, & and -. For example, cs.numeric() - cs.by_name("qty") means all numeric columns except qty.
Filtering rows
A pandas mask is a Series aligned to the frame's index. A Polars predicate is an expression that the filter context evaluates against the frame. You never write the frame's name inside its own condition.
# pandas
paid = pdf[(pdf["status"] == "paid") & (pdf["qty"] > 3)]
# Polars
paid = df.filter((pl.col("status") == "paid") & (pl.col("qty") > 3))
paid = df.filter(pl.col("status") == "paid", pl.col("qty") > 3)The second form passes several predicates to filter, which combines them with AND. Use &, | and ~ for logic, and wrap each comparison in parentheses because those operators bind more tightly than comparisons. Python's and, or and not raise an error on expressions, as they do on pandas Series.
Common predicate helpers:
| pandas | Polars |
|---|---|
| `s.isin(["a", "b"])` | `pl.col("s").is_in(["a", "b"])` |
| `s.between(1, 5)` | `pl.col("s").is_between(1, 5)` |
| `s.isna()` | `pl.col("s").is_null()` |
| `s.notna()` | `pl.col("s").is_not_null()` |
| `s.str.contains("x")` | `pl.col("s").str.contains("x")` |
| `~mask` | `~predicate` |
is_between includes both ends by default, like pandas between. Pass closed="left", "right" or "none" to change that.
There is no query() string syntax. Use expressions, which are checked as ordinary Python code. If you already hold a boolean Series, df.filter(mask_series) also works, but expressions are what the optimizer understands.
Nulls in predicates
A comparison with a null value gives null, not False. filter keeps only rows where the predicate is exactly True, so null rows are dropped. In pandas a NaN compared with > gives False, so the outcome is the same until you negate the condition.
cheap = df.filter(~(pl.col("price") > 6))
cheap_or_missing = df.filter(~(pl.col("price") > 6) | pl.col("price").is_null())In pandas, ~(pdf["price"] > 6) keeps the NaN row, because the inner comparison was False. In Polars the first query drops the null-price row, since ~null is still null. Decide explicitly whether missing values should pass, and say so with is_null() or fill_null.
Sorting
sort_values becomes sort. The argument is descending rather than ascending, and the meaning is inverted.
# pandas
out = pdf.sort_values(["region", "price"], ascending=[True, False])
# Polars
out = df.sort(["region", "price"], descending=[False, True])
out = df.sort("price", descending=True, nulls_last=True)
out = df.sort(pl.col("price") * pl.col("qty"))Three details differ from pandas:
- Null placement. pandas puts NaN last by default (
na_position="last"). Polars puts nulls first in ascending order, so addnulls_last=Trueto reproduce pandas output. - Expressions as keys.
sortaccepts an expression, so you can order by a computed value without creating a temporary column. - Stability. Polars does not guarantee that equal keys keep their input order unless you pass
maintain_order=True. Add it whenever a later step or a test depends on row order.
For the largest or smallest few rows, top_k and bottom_k replace nlargest and nsmallest:
top_two = df.top_k(2, by="price")Rows with a null price are skipped by top_k when enough non-null rows exist, so check the result if nulls are common in your data.
Selecting rows by position
Polars has no index, so there is no loc with labels and no iloc. Label lookups become filters. Positional lookups use slicing methods.
first_three = df.head(3)
last_two = df.tail(2)
middle = df.slice(1, 2)
one_value = df.item(0, "price")slice(offset, length) takes a start and a length, not a start and a stop. item(row, column) returns a single Python value. Avoid indexing a frame in a loop. Positional access is for inspection, and the work belongs in expressions.
How the pieces fit
Each Polars call returns a new frame, so the three steps chain naturally:
report = (
df.filter(pl.col("status") == "paid")
.select("region", "price", "qty")
.sort("price", descending=True, nulls_last=True)
)Checklist when porting
- Replace
df[df[...]]withdf.filter(...)and each column reference withpl.col. - Parenthesize comparisons joined with
&,|or~. - For every negated condition, decide what should happen to null rows.
- Invert
ascendingintodescending, and addnulls_last=Trueto match pandas. - Add
maintain_order=Truewhere tie order matters. - Replace index-based
locandilocwithfilter,head,tailorslice.
Exercise
A pandas line reads pdf[~(pdf["price"] > 6)].sort_values("price"), and price contains NaN. Write a Polars version that returns the same rows in the same order.
Show answer
df.filter(~(pl.col("price") > 6) | pl.col("price").isnull()).sort("price", nullslast=True). The is_null() term keeps the rows that pandas keeps because NaN > 6 is False. nulls_last=True matches pandas, which puts NaN last.
Exercise
What does df.select("region") return, and how does it differ from df.with_columns(pl.col("region").str.to_uppercase())?
Show answer
select returns a new frame containing only the region column. with_columns returns a new frame with all the original columns, with region replaced by its uppercase version.