Sub topic 2
Selecting Many Columns and Computing Per-Group Values
This chapter assumes basic Python, method chaining, and familiarity with rows, columns, and CSV files. The examples use Polars expressions, which describe column operations instead of processing rows one at a time.
Selecting many columns at once
Use pl.col with a list when you know the column names. Use selectors when a group of columns shares a property, such as having numeric data.
import polars as pl
from polars import selectors as cs
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, None, 90],
"joined": ["2024-01-15", "2023-06-01", None, "2022-09-20"],
}
)
print(df.select(pl.col(["name", "dept"]), cs.numeric()))select returns only the expressions requested. In contrast, with_columns keeps existing columns and adds or replaces columns.
Conditional columns with `when`/`then`/`otherwise`
A conditional expression creates values from a Boolean condition.
prepared = (
df.with_columns(
pl.when(pl.col("salary").is_null())
.then(pl.lit("unknown"))
.when(pl.col("salary") >= 100)
.then(pl.lit("high"))
.otherwise(pl.lit("standard"))
.alias("band"),
pl.col("name").str.to_uppercase().alias("name_upper"),
)
.with_columns(
pl.col("joined").str.to_date(strict=False).alias("joined")
)
.with_columns(
pl.col("joined").dt.year().alias("join_year")
)
)Working with null values
A null means that a value is missing. Comparisons with null produce null, not True or False. Handle missing values explicitly with is_null, fill_null, or coalesce. Aggregations such as mean skip null values, while len counts rows.
String and datetime expressions
Polars namespaces group related operations. The str namespace handles text, and the dt namespace handles dates and times. These operations remain native Polars expressions.
Grouping and aggregating
group_by reduces several rows into one row per group. Use agg for one or more aggregate expressions.
summary = (
prepared.group_by("dept")
.agg(
pl.col("salary").mean().alias("avg_salary"),
pl.col("salary").count().alias("known_salaries"),
pl.len().alias("headcount"),
)
.sort("dept")
)
print(summary)Per-group values with `over()`
A window expression computes within each group but keeps every original row. This differs from group_by, which collapses rows.
| Need | Use |
|---|---|
| One result row per department | `group_by("dept").agg(...)` |
| Department value on every employee row | `pl.col(...).over("dept")` |
with_department_average = prepared.with_columns(
pl.col("salary").mean().over("dept").alias("dept_avg")
)
print(with_department_average)Exercise
Which operation should you use to keep every employee row while adding that employee's department average?
Show answer
Use a window expression such as pl.col("salary").mean().over("dept").