Sub topic 5
Expressions and contexts: select, with_columns, filter, agg
This chapter assumes you know pandas DataFrames and Series, basic Python, and how to install Polars with pip install polars.
Expressions describe work
An expression is a description of a computation, not its result. pl.col("price") * pl.col("qty") does nothing on its own. It runs when you pass it to a context, which is a method that decides what the expression operates on and what shape comes back.
In pandas, pdf["price"] * pdf["qty"] runs at once and returns a Series aligned on the index. Polars has no index, so an expression needs nothing to align to. You can name it, store it in a variable, and reuse it in several contexts.
The four contexts
| Polars context | Closest pandas idiom | Result |
|---|---|---|
| `select` | `pdf[["a", "b"]]` or computed columns | Only the expressions you list |
| `with_columns` | `pdf.assign(...)` | All existing columns, plus new or replaced ones |
| `filter` | `pdf[mask]` | Rows where the expression is true |
| `group_by(...).agg` | `pdf.groupby(...).agg(...)` | One row per group |
One expression, four contexts
import polars as pl
df = pl.DataFrame({
"region": ["north", "south", "north", "east"],
"price": [10.0, 40.0, 25.0, 5.0],
"qty": [3, 4, 5, 2],
})
total = pl.col("price") * pl.col("qty")
selected = df.select("region", total.alias("total"))
extended = df.with_columns(total.alias("total"))
large = extended.filter(pl.col("total") > 100)
summary = df.group_by("region", maintain_order=True).agg(
total.sum().alias("revenue")
)
print(summary)selected has two columns. extended has the original three plus total. large keeps the south and north rows with totals of 160 and 125. summary has one row per region. Polars does not guarantee group order, so maintain_order=True keeps the first-seen order.
Common errors
- Expecting sequential evaluation. All expressions in one call run independently on the input frame.
df.with_columns(a=pl.col("qty") * 2, b=pl.col("a") + 1)fails becauseadoes not exist yet. Split it into twowith_columnscalls. - Using Python
andoror. Combine conditions with&and|, and wrap each comparison in parentheses:(pl.col("qty") > 2) & (pl.col("price") < 30). - Assigning with brackets.
df["total"] = ...is not the Polars style. Frames are immutable, so assign the result ofwith_columnsto a variable. - Forgetting
aggis an expression context. Insideagg,pl.col("total")means the whole group's column, so you reduce it with.sum()or.mean().
Exercise
Using the df above, write one call that returns only the rows where region is "north", with a new column total and no other new columns. Which two contexts do you need?
Show answer
df.withcolumns(total.alias("total")).filter(pl.col("region") == "north"). You need withcolumns to add the column and filter to keep the rows. Using filter first is also valid: df.filter(pl.col("region") == "north").with_columns(total.alias("total")).