Sub topic 5
Expressions and contexts: select, with_columns, filter, agg
This chapter assumes you know pandas DataFrames and Series, can read Python method chains and lambdas, and have Polars installed (pip install polars). It builds on the mental model of no index and immutable frames. Here you learn the two ideas that replace most pandas indexing code: expressions and contexts.
An expression is a recipe, not data
In pandas, df["price"] * df["qty"] computes a Series right away. In Polars, pl.col("price") * pl.col("qty") computes nothing. It is an expression, a description of a calculation. The expression runs only when you hand it to a context, which is a DataFrame method that supplies the data and decides what to do with the result.
import polars as pl
total = pl.col("price") * pl.col("qty")
print(type(total))
print(total)The output shows an Expr object, not numbers. Because an expression is a plain Python object, you can store it in a variable, return it from a function, and reuse it in several contexts. That is the main way to share logic in Polars code.
The four contexts
| Context | What it does | Rows in the result | pandas analogue |
|---|---|---|---|
| `select` | Returns only the columns the expressions produce | Same as the input, or one row if the expressions aggregate | `df[["a", "b"]]`, or a new frame built from Series |
| `with_columns` | Keeps all existing columns and adds or replaces the ones you give | Same as the input | `df.assign(...)` |
| `filter` | Keeps rows where a boolean expression is true | Fewer or equal | `df[mask]` |
| `group_by(...).agg(...)` | Evaluates expressions once per group | One per group | `groupby().agg(...)` |
All four return a new DataFrame. The original is never changed.
select versus with_columns
Use select when you want exactly the columns you name. Use with_columns when you want to keep everything and add or overwrite columns.
import polars as pl
df = pl.DataFrame(
{
"region": ["east", "west", "east", "west"],
"price": [10.0, 20.0, 30.0, 40.0],
"qty": [1, 2, 5, 3],
}
)
# Only two columns come back
small = df.select("region", (pl.col("price") * pl.col("qty")).alias("total"))
# All original columns, plus total
full = df.with_columns(total=pl.col("price") * pl.col("qty"))
print(small)
print(full)There are two ways to name an output column. You can call .alias("total") on the expression, or pass a keyword argument such as total=.... Without either, the output takes the name of the leftmost column in the expression, so pl.col("price") * pl.col("qty") would be named price. If a new name matches an existing column, with_columns replaces that column in place within the new frame.
Aggregating expressions and broadcasting
An expression that reduces a column to one value behaves differently depending on its context. In select it produces a one-row result. In with_columns the single value is broadcast to every row.
import polars as pl
df = pl.DataFrame({"price": [10.0, 20.0, 30.0, 40.0], "qty": [1, 2, 5, 3]})
df = df.with_columns(total=pl.col("price") * pl.col("qty"))
# One row: the total of all totals
print(df.select(pl.col("total").sum().alias("grand_total")))
# Four rows: each total minus the overall mean (80.0)
print(df.with_columns(diff=pl.col("total") - pl.col("total").mean()))This replaces the pandas habit of computing df["total"].mean() into a variable and then using it. The mean stays inside the expression, so the whole step is one declaration.
Expressions in the same context do not see each other
All expressions passed to one select or with_columns call are evaluated against the same input frame, and Polars may run them in parallel. A column created in a call is not visible to other expressions in that call.
import polars as pl
df = pl.DataFrame({"price": [10.0, 20.0], "qty": [1, 2]})
try:
df.with_columns(
total=pl.col("price") * pl.col("qty"),
big=pl.col("total") > 15,
)
except pl.exceptions.ColumnNotFoundError as err:
print("Fails:", err)
# Fix: chain two calls, or repeat the expression
ok = df.with_columns(total=pl.col("price") * pl.col("qty")).with_columns(
big=pl.col("total") > 15
)
print(ok)In pandas you could assign total and read it on the next line. In Polars each with_columns call is a step, and later steps see earlier results.
Filtering with boolean expressions
filter takes an expression that yields booleans. There is no mask indexed from the frame.
import polars as pl
df = pl.DataFrame(
{
"region": ["east", "west", "east", "west"],
"qty": [1, 2, 5, 3],
}
)
# Several predicates are combined with AND
east_big = df.filter(pl.col("region") == "east", pl.col("qty") > 1)
# Explicit operators need parentheses around each side
either = df.filter((pl.col("region") == "east") | (pl.col("qty") > 2))
not_east = df.filter(~(pl.col("region") == "east"))
print(east_big)
print(either)
print(not_east)Use &, | and ~, not and, or and not. Python's keywords try to turn the whole expression into a single bool, which raises an error. Operator precedence in Python makes pl.col("a") == 1 | pl.col("b") == 2 parse wrongly, so wrap each comparison in parentheses.
A row where the predicate evaluates to null is dropped, the same as a row where it is false.
Working on many columns at once
An expression can name several columns, and the operation then applies to each one.
import polars as pl
df = pl.DataFrame(
{
"region": ["east", "west"],
"price": [10.0, 20.0],
"cost": [4.0, 9.0],
}
)
# Round every float column, keeping the original names
rounded = df.with_columns(pl.col(pl.Float64).round(0))
# Select by name list, and use pl.all() or pl.exclude()
sums = df.select(pl.col("price", "cost").sum())
others = df.select(pl.exclude("region"))
print(rounded)
print(sums)
print(others)When one expression produces several columns, each keeps its own name. If you add .alias, you can name only a single output. For bulk renaming use .name.suffix("_x") or .name.prefix("x_").
Expressions inside group_by
In an aggregation context the same expressions run once per group.
import polars as pl
df = pl.DataFrame(
{
"region": ["east", "west", "east", "west"],
"price": [10.0, 20.0, 30.0, 40.0],
"qty": [1, 2, 5, 3],
}
)
summary = (
df.group_by("region", maintain_order=True)
.agg(
(pl.col("price") * pl.col("qty")).sum().alias("revenue"),
pl.len().alias("orders"),
)
)
print(summary)The multiplication happens inside agg, so no helper total column is needed first. Groups come back in arbitrary order unless you pass maintain_order=True or sort afterward.
Common errors when porting
- Reading a column created in the same call. Split the work into chained
with_columnscalls. - Using
df["col"] = .... Frames do not support this pattern for new columns in normal Polars code. Usewith_columnsand assign the result. - Using
and,or,not. Switch to&,|,~with parentheses. - Expecting an index to align results. Expressions work by position within the frame. Nothing is matched on labels.
- Selecting one column and expecting a DataFrame.
df["a"]returns a Series.df.select("a")returns a one-column DataFrame.
Exercise
Given df with columns "price" and "qty", you write df.with_columns(total=pl.col("price") * pl.col("qty"), share=pl.col("total") / pl.col("total").sum()). It raises ColumnNotFoundError. Why, and how do you fix it?
Show answer
Expressions in one withcolumns call all read the input frame, so "total" does not exist yet when "share" is evaluated. Fix it by chaining two calls: df.withcolumns(total=pl.col("price") * pl.col("qty")).with_columns(share=pl.col("total") / pl.col("total").sum()). The sum is a one-value result that is broadcast across all rows.