Sub topic 6
Selecting, filtering and sorting
This chapter assumes you know pandas loc, boolean masks and sort_values, and that you have read the earlier chapters on expressions and contexts. Here you will translate the three most common row and column operations.
Selecting columns
pandas selects columns with df[["a", "b"]] or loc. Polars uses select, which takes column names or expressions and returns a new DataFrame.
import polars as pl
import polars.selectors as cs
df = pl.DataFrame(
{
"order_id": [1, 2, 3, 4, 5],
"region": ["EU", "US", "EU", "EU", "US"],
"price": [10.0, 25.0, None, 40.0, 5.0],
"qty": [3, 5, 2, 4, 0],
}
)
by_name = df.select("order_id", "price")
numeric = df.select(cs.numeric())
no_qty = df.select(pl.all().exclude("qty"))
by_regex = df.select(pl.col("^(price|qty)$"))Selectors such as cs.numeric() replace pandas calls like select_dtypes. Use df.drop("qty") when you only want to remove columns.
Filtering rows
pandas indexes the frame with a boolean mask, as in pdf[pdf["qty"] > 0]. Polars passes an expression to filter. Several predicates passed as separate arguments are combined with AND, so you don't need & between them.
eu_orders = df.filter(
pl.col("qty") > 0,
pl.col("region") == "EU",
)
picked = df.filter(
pl.col("region").is_in(["EU", "US"]),
pl.col("price").is_between(10, 30),
)When you do combine conditions inside one expression, use &, | and ~, and wrap each comparison in parentheses. The Python keywords and and or fail here, as they do in pandas.
There is no loc or iloc. For positions, use df.head(3), df.tail(3) or df.slice(1, 2), which starts at offset 1 and takes 2 rows.
Sorting
sort_values becomes sort. The ascending argument becomes descending, and its meaning is reversed.
ranked = df.sort(["region", "price"], descending=[False, True], nulls_last=True)
top_two = df.top_k(2, by="price")- Polars places nulls first by default, while pandas places NaN last. Pass
nulls_last=Trueto match pandas. - Pass
maintain_order=Trueif ties must keep their original order, as in a stable sort. - Because there is no index,
sortleaves nothing to reset. You never callreset_indexafterwards.
Quick reference
| pandas | Polars |
|---|---|
| `df[["a", "b"]]` | `df.select("a", "b")` |
| `df.drop(columns=["a"])` | `df.drop("a")` |
| `df[df["a"] > 1]` | `df.filter(pl.col("a") > 1)` |
| `df["a"].isin(vals)` | `pl.col("a").is_in(vals)` |
| `df.sort_values("a", ascending=False)` | `df.sort("a", descending=True)` |
| `df.nlargest(2, "a")` | `df.top_k(2, by="a")` |
| `df.iloc[:5]` | `df.head(5)` |
Exercise
Port this pandas code to Polars: pdf[(pdf["qty"] > 0) & (pdf["region"] == "US")].sort_values("price", ascending=False)[["order_id", "price"]]. Where do null prices end up in your result by default?
Show answer
df.filter(pl.col("qty") > 0, pl.col("region") == "US").sort("price", descending=True).select("order_id", "price"). With descending=True and the default nulls_last=False, null prices appear first. Pass nulls_last=True to put them at the end, as pandas does.