Sub topic 5
Selecting many columns at once
This chapter assumes you know how select and with_columns work and what an expression is. It shows how to apply one expression to many columns without typing each name.
Why select in bulk
Wide tables can have dozens of columns. Writing the same operation for each one is tedious and easy to get wrong. Polars lets one expression expand into one expression per matching column. You write the logic once, and Polars applies it to every column that matches.
The examples use this DataFrame:
import polars as pl
import polars.selectors as cs
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy"],
"dept": ["eng", "eng", "ops"],
"salary_base": [120, 100, 80],
"salary_bonus": [10, 5, 0],
"age": [31, 45, 28],
}
)Expanding pl.col
pl.col accepts several forms. Each one expands to multiple columns.
print(df.select(pl.col("salary_base", "salary_bonus")))
print(df.select(pl.col("^salary_.*$")))
print(df.select(pl.col(pl.Int64)))
print(df.select(pl.all()))
print(df.select(pl.exclude("name", "dept")))- Several names select exactly those columns.
- A string that starts with
^and ends with$is a regular expression. - A data type selects every column of that type.
pl.all()selects every column, andpl.exclude(...)selects all except the ones you list.
Any operation after the selection is applied to each matched column separately, and each result keeps its source column's name:
print(df.select(pl.col("^salary_.*$") * 1.1))Selectors
The polars.selectors module, imported above as cs, gives readable names to common patterns.
print(df.select(cs.numeric()))
print(df.select(cs.string()))
print(df.select(cs.starts_with("salary")))
print(df.select(cs.contains("a")))Selectors combine with set operators, so you can describe a selection precisely:
| Operator | Meaning | Example | Column | Column |
|---|---|---|---|---|
| `\ | ` | union | `cs.string() \ | cs.starts_with("sal")` |
| `&` | intersection | `cs.numeric() & cs.starts_with("salary")` | ||
| `-` | difference | `cs.numeric() - cs.starts_with("salary")` | ||
| `~` | complement | `~cs.string()` |
print(df.select(cs.numeric() - cs.starts_with("salary")))This returns only age.
Bulk transformations and naming
A bulk expression keeps the original column names. That is fine in select, but in with_columns the results would overwrite the originals. To keep both, rename the outputs with the name namespace:
out = df.with_columns(
(cs.starts_with("salary_") / 1000).name.suffix("_k")
)
print(out.columns)The result has the original five columns plus salary_base_k and salary_bonus_k. Aggregations expand the same way:
print(df.select(cs.numeric().mean()))
print(df.group_by("dept").agg(cs.numeric().max()).sort("dept"))Common mistakes
- A bulk expression that matches a column you did not intend to change. Selectors such as
cs.numeric()include every numeric column, so subtract the ones to skip. - Applying an arithmetic operation to a selection that includes a string column. Narrow the selection by type first.
- Forgetting that outputs keep their input names. If two expressions in one
selectproduce the same name, Polars raises a duplicate-column error, so rename one of them.
Exercise
Write a with_columns call on df that adds a "_pct" suffix to a copy of every numeric column except age, where each copy is the original value divided by 100.
Show answer
df.withcolumns((cs.numeric() - cs.byname("age"))._truediv(100).name.suffix("pct")) works, but the clearer form is: df.withcolumns(((cs.numeric() - cs.byname("age")) / 100).name.suffix("_pct")). The selector difference removes age, the division applies to each remaining numeric column, and name.suffix keeps the originals by giving the copies new names.