Sub topic 1
Expressions and contexts: the building blocks
Prerequisites
This chapter assumes you can:
- Read and write basic Python, including keyword arguments and
try/except. - Think of a table as rows, columns, and key columns.
- Create a Polars
DataFrameand refer to a column withpl.col.
Everything later in this tutorial (grouping, joins, windows) is built from the two ideas here. An expression describes a computation. A context decides what that computation sees and what shape the result has.
What an expression is
An expression is a description of a computation on columns. It is not data. When you write pl.col("sales") * 2, nothing is calculated. You get an object that records "take the sales column and multiply it by 2". Polars runs it only when you hand it to a context.
import polars as pl
expr = pl.col("sales").sum().alias("total")
print(type(expr)) # <class 'polars.expr.expr.Expr'>
print(expr) # a description of the computation, not a numberBecause an expression is a value, you can store it in a variable, pass it to functions, and reuse it in several places. Polars can also inspect all the expressions in a call together. That lets it run independent ones in parallel and, in lazy mode, optimize across them.
An expression has three parts you will see throughout this tutorial:
- A source, such as
pl.col("sales")orpl.lit(1). - Operations chained on it, such as
.sum(),.filter(...),.rank(), or arithmetic. - An output name, which defaults to the name of the leftmost column and can be changed with
.alias(...).
What a context is
A context is the place an expression is evaluated. The context controls three things: which rows the expression sees, how many rows the result has, and what happens to the other columns.
| Context | Rows the expression sees | Result shape | Other columns |
|---|---|---|---|
| `select` | The whole frame | Only the columns you list | Dropped |
| `with_columns` | The whole frame | Same height as the input | Kept (same-name columns are replaced) |
| `filter` | The whole frame | Fewer or equal rows | Kept |
| `group_by(...).agg` | One group at a time | One row per group | Group keys plus your aggregates |
The same expression can behave very differently depending on its context. The next sections show this with one small table. The later code blocks reuse the df defined in the first one.
select and with_columns
select builds a new frame from only the expressions you give it. with_columns starts from the existing frame and adds or replaces columns.
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"product": ["a", "b", "a", "b", "b"],
"sales": [10, 20, 5, 15, 25],
})
picked = df.select(
pl.col("region"),
(pl.col("sales") * 2).alias("double_sales"),
pl.col("sales").sum().alias("total"),
)
print(picked)
# 5 rows, 3 columns. total is 75 on every row.
widened = df.with_columns(
share=pl.col("sales") / pl.col("sales").sum(),
)
print(widened)
# 5 rows, 4 columns: region, product, sales, share.Two details in this code matter:
pl.col("sales").sum()produces a single value, but the frame has five rows. Polars broadcasts a length-1 result, which means it repeats the value to match the other columns. That is whytotalis 75 on every row.share=...is shorthand for.alias("share"). Keyword arguments are a compact way to name outputs.
If an expression keeps the name of an existing column, with_columns replaces that column. df.with_columns(pl.col("sales") * 2) returns the same columns as df, with doubled sales values.
Length rules inside a context
In select and with_columns, every output must have the same length, or length 1 to be broadcast. If lengths disagree, Polars raises a ShapeError instead of guessing.
try:
df.select(pl.col("sales").head(2), pl.col("region"))
except pl.exceptions.ShapeError as err:
print("ShapeError:", err)The first expression yields 2 values and the second yields 5. Neither is length 1, so the call fails.
Expressions in one call do not see each other
Expressions in a single select or with_columns call are evaluated in parallel against the input frame. A column created by one expression is not visible to its siblings in the same call.
try:
df.with_columns(
doubled=pl.col("sales") * 2,
plus_one=pl.col("doubled") + 1,
)
except pl.exceptions.ColumnNotFoundError as err:
print("ColumnNotFoundError:", err)
# Fix: chain two calls, or repeat the logic in the second expression.
ok = (
df.with_columns(doubled=pl.col("sales") * 2)
.with_columns(plus_one=pl.col("doubled") + 1)
)
print(ok)The same rule applies inside agg. You cannot refer to one aggregate by name inside another aggregate in the same call. Chain a second step on the result instead.
Output names and duplicates
Every output column needs a unique name. Two expressions rooted in the same column both default to that column's name, so they collide.
try:
df.select(pl.col("sales").sum(), pl.col("sales").mean())
except pl.exceptions.DuplicateError as err:
print("DuplicateError:", err)
stats = df.select(
pl.col("sales").sum().alias("sales_sum"),
pl.col("sales").mean().alias("sales_mean"),
)
print(stats) # sales_sum 75, sales_mean 15.0Get in the habit of calling .alias(...) on every aggregate. It prevents this error and makes your output readable.
Selecting many columns with one expression
pl.col accepts several names, a dtype, or a regular expression. The operations after it are applied to each selected column, and each output keeps its own column name.
print(df.select(pl.col(pl.Int64).sum())) # sales: 75
print(df.select(pl.col("region", "product").n_unique()))
# region: 2, product: 2This is what makes expressions composable. One short expression can summarize ten columns, and in a later chapter it will do the same per group.
The same expression in three contexts
Take pl.col("sales").sum() and move it between contexts.
total = pl.col("sales").sum().alias("total")
print(df.select(total)) # 1 row: total 75
print(df.with_columns(total)) # 5 rows, total 75 on each
print(df.group_by("region").agg(total).sort("region"))
# 2 rows: east 30, west 45The expression is identical in all three calls. In select it sees the whole column and returns one row. In with_columns the one value is broadcast to the frame height. In group_by(...).agg it runs once per group on only that group's rows.
This is the model to keep in mind for the whole tutorial. The next chapters add contexts and modifiers (group_by, over, joins) that change which rows an expression sees and how its result is lined up with the original table.
Boolean expressions and filter
filter is a context too. It takes a boolean expression and keeps the rows where it is true.
big = df.filter(pl.col("sales") > 10)
print(big) # 3 rows: sales 20, 15, 25
east_big = df.filter(
(pl.col("region") == "east") & (pl.col("sales") > 10)
)
print(east_big) # 1 row: east, b, 20Combine conditions with &, |, and ~, and put parentheses around each comparison. Python's and and or do not work on expressions.
Expr.filter also exists as a method on an expression. It restricts only that expression to matching rows, and it is the basis of conditional aggregation in a later chapter.
Eager and lazy use the same expressions
Everything above ran on a DataFrame, which executes each call immediately. The same expressions work on a LazyFrame, which records the whole query and runs it when you call .collect().
lazy_out = (
df.lazy()
.filter(pl.col("sales") > 5)
.group_by("region")
.agg(pl.col("sales").sum().alias("total"))
.sort("region")
.collect()
)
print(lazy_out) # east: 30, west: 40You write expressions once. Choosing eager or lazy only changes when the work happens. Lazy mode lets Polars reorder and prune steps before running them. The last chapter returns to this.
Common mistakes
- Expecting a result from an expression alone.
pl.col("sales").sum()is a description, so you must pass it to a context. - Using
selectwhen you wanted to keep the other columns. Usewith_columns. - Forgetting
.aliason two aggregates of the same column. - Referring to a column created earlier in the same call.
- Mixing result lengths in
selectthat are neither equal nor 1.
Exercise
Given the df above, write one with_columns call that adds a column pct_of_total holding each row's sales divided by the overall sales total, and a column is_big that is true when sales exceed the overall mean. Why does this work in a single call even though both columns use an aggregate?
Show answer
df.withcolumns(pctoftotal=pl.col("sales") / pl.col("sales").sum(), isbig=pl.col("sales") > pl.col("sales").mean()). Inside with_columns, sum() and mean() each return one value that is broadcast against the five-row sales column. Neither new column depends on the other, so one call is enough.
Exercise
You run df.select(pl.col("sales").min(), pl.col("sales").max()) and get a DuplicateError. What is the cause and the fix?
Show answer
Both expressions default to the output name "sales", and a frame cannot have two columns with the same name. Add aliases, for example pl.col("sales").min().alias("salesmin") and pl.col("sales").max().alias("salesmax").