Sub topic 1
Expressions and contexts: the building blocks
Prerequisites
This chapter assumes you can write basic Python and create a Polars DataFrame. It also assumes you can select a column with pl.col, and that you know what rows, columns and keys are. Every later chapter on grouping, joining and windows builds on the two ideas here.
What an expression is
An expression is a description of a computation. It does not hold data and does not run when you create it. pl.col("sales").sum() only says "take the sales column and add it up". Polars runs it when you hand it to a context.
A context is a DataFrame method that decides which rows the expression sees and what shape the result has. The main contexts are select, with_columns, filter and group_by(...).agg.
The same expression in different contexts
The examples below use one small DataFrame.
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],
})
total = pl.col("sales").sum().alias("total")
print(df.select(total))
print(df.group_by("region").agg(total).sort("region"))The expression total is defined once and used twice. In select, it sees the whole table and returns one row with a total of 75. In group_by("region").agg, it sees one group at a time. The result is one row per region: east is 30 and west is 45.
select and with_columns
select returns only the columns you ask for. with_columns returns every original column plus the new or replaced ones.
doubled = df.with_columns((pl.col("sales") * 2).alias("sales_x2"))
print(doubled.shape) # (5, 4)
only = df.select(
pl.col("region"),
(pl.col("sales") * 2).alias("sales_x2"),
)
print(only.shape) # (5, 2)Both calls keep five rows, because pl.col("sales") * 2 produces one value per input row. An aggregation such as sum() produces a single value. In select it gives one row. In with_columns Polars repeats that single value on every row.
Naming and composing
Use alias to name a result. Without it, the output column takes the name of the first column in the expression, and two results with the same name raise an error. Pass several expressions to one context and Polars evaluates them in parallel.
out = df.select(
pl.col("sales").sum().alias("total"),
pl.col("sales").mean().alias("average"),
pl.col("sales").max().alias("largest"),
)
print(out) # one row: 75, 15.0, 25Common errors
- Writing
df["sales"].sum()and expecting an expression. That is a plain Series method and runs immediately, so you cannot reuse it insideagg. - Forgetting
aliaswhen two expressions would produce the same output name. Polars raises a duplicate column error. - Using
selectwhen you wanted to keep the other columns. Switch towith_columns.
Exercise
You run df.select(pl.col("sales").sum()) and df.with_columns(pl.col("sales").sum()). What shape does each call return for the five-row DataFrame above?
Show answer
The select call returns 1 row and 1 column, because only the new aggregated column is kept. The with_columns call returns 5 rows and 3 columns, because the sum of 75 is repeated on every row and replaces the existing sales column.