Sub topic 1
Expressions, Grouping, and Joins in Polars
Prerequisites
Assume you know basic Python, DataFrame rows and columns, and pl.col for selecting Polars columns.
Expressions and contexts: the building blocks
A Polars expression describes a computation, such as pl.col("sales").sum(). It does not calculate a result until a context evaluates it. Common contexts include:
select: creates a new set of columns.with_columns: adds or replaces columns while keeping existing rows.agg: reduces rows into summary values.filter: keeps rows that match a condition.
The same expression can produce different results depending on its context.
Summarizing groups with `group_by` and `agg`
group_by partitions a DataFrame by one or more key columns. agg then evaluates expressions separately for each partition. The result has one row per group.
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],
})
summary = (
df.group_by("region")
.agg(
pl.col("sales").sum().alias("total"),
pl.len().alias("rows"),
)
.sort("region")
)
print(summary)Multiple and conditional aggregations
An aggregation can filter its input expression before calculating. This lets one group_by produce several related measures.
summary = df.group_by("region").agg(
pl.col("sales")
.filter(pl.col("product") == "b")
.sum()
.alias("b_sales"),
pl.col("sales").mean().alias("average_sales"),
)Here, b_sales includes only product b, while average_sales includes every product.
Group order and `maintain_order`
Group order is not guaranteed by default. Sort the result when you need deterministic output. Use maintain_order=True when the groups should follow their first appearance in the input. This can cost more than the default grouping strategy, so use it only when input order matters.
Combining tables with inner and left joins
A join combines rows using matching key values. An inner join keeps only matching rows. A left join keeps every row from the left DataFrame and fills missing right-side columns with null.
customers = pl.DataFrame({
"customer_id": [1, 2],
"name": ["Ana", "Ben"],
})
orders = pl.DataFrame({
"order_id": [100, 101],
"customer_id": [1, 3],
})
inner = orders.join(customers, on="customer_id", how="inner")
left = orders.join(customers, on="customer_id", how="left")The inner result contains order 100 only. The left result keeps both orders, with a null name for order 101.
Exercise
Which context should you use to produce one summary row per region, and which join keeps unmatched orders?
Show answer
Use group_by("region").agg(...) for one summary row per region, and use a left join to keep unmatched orders.