Sub topic 5
Selecting many columns at once
This chapter assumes you can write select and with_columns calls with pl.col, and that you know Polars infers a dtype for every column. You don't need to know the selectors module. By the end you will be able to pick columns by name, regex, dtype or name pattern, and to combine those picks with set operations.
Why one expression can mean many columns
So far each pl.col("x") has named a single column. Real tables have dozens of columns with shared traits: all the numeric ones, all the ones ending in _cost, everything except the key. Writing one expression per column is tedious and breaks when a column is added.
Polars solves this with expression expansion. If an expression refers to several columns, Polars copies it once per column before running it. The columns are then processed independently.
The examples below use this DataFrame:
import polars as pl
import polars.selectors as cs
df = pl.DataFrame(
{
"id": [1, 2, 3],
"name": ["Ana", "Ben", "Cy"],
"dept": ["eng", "eng", "ops"],
"q1_sales": [100, 150, 80],
"q2_sales": [120, 130, 90],
"q1_cost": [60.0, 90.0, 50.0],
"q2_cost": [70.0, 80.0, 55.0],
}
)
print(df.schema)id, q1_sales and q2_sales are Int64. q1_cost and q2_cost are Float64. name and dept are String.
Several selections with pl.col
pl.col accepts more than one argument, and it accepts things other than plain names.
# Several names
print(df.select(pl.col("q1_sales", "q2_sales")).columns)
# ['q1_sales', 'q2_sales']
# A dtype (or several dtypes)
print(df.select(pl.col(pl.Float64)).columns)
# ['q1_cost', 'q2_cost']
print(df.select(pl.col(pl.Int64, pl.Float64)).columns)
# ['id', 'q1_sales', 'q2_sales', 'q1_cost', 'q2_cost']
# A regular expression
print(df.select(pl.col(r"^q\d_sales$")).columns)
# ['q1_sales', 'q2_sales']
# Everything, and everything except some columns
print(df.select(pl.all()).columns)
print(df.select(pl.exclude("id", "name", "dept")).columns)Two rules for pl.col cause most of the errors:
- A string is treated as a regex only if it starts with
^and ends with$. Without both anchors,pl.col("q\d_sales")looks for a column with that literal name and fails with aColumnNotFoundError. - One call takes names or dtypes, not a mix of both.
pl.col("id", pl.Float64)is an error.
What happens after selection
Once an expression selects several columns, every method you chain applies to each one. The result's shape depends on the context.
In with_columns, an expression that keeps the input names overwrites those columns in place:
rounded = df.with_columns(pl.col(pl.Float64) / 10)
print(rounded.columns)
# same seven columns, with q1_cost and q2_cost divided by 10In select, the same expression returns only the selected columns, transformed.
You can't give several outputs one name, so alias fails on a multi-column expression:
# DuplicateError: both outputs would be called "adjusted"
# df.select((pl.col(pl.Float64) * 1.1).alias("adjusted"))Use the name namespace to derive output names from the input names instead:
adjusted = df.select(
(pl.col(r"^q\d_cost$") * 1.1).name.suffix("_adj")
)
print(adjusted.columns)
# ['q1_cost_adj', 'q2_cost_adj']name.prefix, name.suffix, name.to_uppercase, name.to_lowercase and name.map all work this way. name.map takes a function from the old name to the new name.
The selectors module
pl.col can't express "numeric columns starting with q1" in one call. The polars.selectors module (imported here as cs) is built for that. A selector describes a set of columns. You can combine selectors with set operations, then use the result anywhere an expression is accepted.
| Selector | Matches |
|---|---|
| `cs.numeric()` | Integer, float and decimal columns |
| `cs.integer()`, `cs.float()` | Integer columns, float columns |
| `cs.string()` | String columns |
| `cs.by_dtype(pl.Int64)` | Columns of exactly that dtype |
| `cs.by_name("id", "name")` | Columns with those names |
| `cs.starts_with("q1")` | Names starting with the prefix |
| `cs.ends_with("sales", "cost")` | Names ending with any listed suffix |
| `cs.contains("_")` | Names containing the substring |
| `cs.matches(r"q\d_.*")` | Names matching a regex (no `^`/`$` needed) |
| `cs.first()`, `cs.last()` | The first or last column |
| `cs.all()` | Every column |
Selectors are more readable than pl.col regexes because the intent is in the function name. They also handle several suffixes or prefixes in one call.
print(df.select(cs.numeric()).columns)
# ['id', 'q1_sales', 'q2_sales', 'q1_cost', 'q2_cost']
print(df.select(cs.starts_with("q1")).columns)
# ['q1_sales', 'q1_cost']
print(df.select(cs.ends_with("sales", "cost")).columns)
# ['q1_sales', 'q2_sales', 'q1_cost', 'q2_cost']Combining selectors with set operations
Selectors support four operators, which behave like Python sets of columns.
| Operator | Meaning | Example | Column | Column |
|---|---|---|---|---|
| `\ | ` | Union | `cs.string() \ | cs.by_name("id")` |
| `&` | Intersection | `cs.numeric() & cs.ends_with("sales")` | ||
| `-` | Difference | `cs.numeric() - cs.by_name("id")` | ||
| `~` | Complement | `~cs.string()` |
sales_cols = cs.numeric() & cs.ends_with("sales")
measures = cs.numeric() - cs.by_name("id")
non_text = ~cs.string()
print(df.select(sales_cols).columns) # ['q1_sales', 'q2_sales']
print(df.select(measures).columns) # ['q1_sales', 'q2_sales', 'q1_cost', 'q2_cost']
print(df.select(non_text).columns) # ['id', 'q1_sales', 'q2_sales', 'q1_cost', 'q2_cost']The operators act as set operations only when both sides are selectors. If one side is an ordinary expression, - is subtraction and & is a boolean AND. Once you call an expression method on a selector, such as .sum(), the result is an ordinary expression and loses its set behavior.
Using selections in every context
A selector works wherever an expression does, and in a few places that need column names.
# Row-wise total across a group of columns
totals = df.select(
"name",
pl.sum_horizontal(cs.ends_with("sales")).alias("total_sales"),
)
print(totals)
# Grouped aggregation over many columns at once
by_dept = (
df.group_by("dept")
.agg(cs.ends_with("sales", "cost").sum().name.suffix("_sum"))
.sort("dept")
)
print(by_dept.columns)
# ['dept', 'q1_sales_sum', 'q2_sales_sum', 'q1_cost_sum', 'q2_cost_sum']
# Selectors can also be group keys
print(df.group_by(cs.string()).len().height)pl.sum_horizontal takes a selector here, so alias is fine because it returns a single column. Selectors also work in DataFrame.select, drop, unique(subset=...) and sort.
without_text = df.drop(cs.string())
print(without_text.columns)Checking what a selector matches
A selector that matches nothing doesn't raise an error. It expands to zero columns, and your select quietly returns an empty frame. A typo such as cs.ends_with("sale") is therefore easy to miss. Use cs.expand_selector to see exactly which names a selector resolves to:
print(cs.expand_selector(df, cs.numeric() - cs.by_name("id")))
# ('q1_sales', 'q2_sales', 'q1_cost', 'q2_cost')This is useful in tests and in pipelines where the incoming columns can change.
Choosing a tool
The diagram shows how to pick a selection method.
Use pl.col for quick, explicit picks. Switch to selectors when you combine criteria or when the rule should survive new columns being added.
Common errors
- Missing anchors in a regex.
pl.col(r"q\d_sales")is a literal name. Add^and$. aliason an expansion. Usename.suffix,name.prefixorname.map.- Mixing names and dtypes in
pl.col. Split them into two selectors and union them withcs.by_name(...) | cs.by_dtype(...). - Assuming
cs.numeric()excludes keys. Anidcolumn is an integer, so it is numeric. Subtract it explicitly. - Silent empty matches. Verify patterns with
cs.expand_selector.
Exercise
Using the DataFrame from this chapter, write one with_columns call that adds a new column for each cost column. The new columns should be named q1_cost_k and q2_cost_k, and each should hold the cost divided by 1000. Which selector and name method do you use, and why can't you use alias?
Show answer
Use df.with_columns((cs.ends_with("cost") / 1000).name.suffix("_k")). The selector cs.ends_with("cost") expands to q1_cost and q2_cost. name.suffix("_k") derives q1_cost_k and q2_cost_k, so the originals are kept. alias would give both outputs the same name, which raises a duplicate-name error.
Exercise
Write a selector that picks every numeric column except id and any column whose name ends in cost. Then name the function that shows which columns it matched.
Show answer
cs.numeric() - cs.by_name("id") - cs.ends_with("cost"), which matches q1_sales and q2_sales. Check it with cs.expand_selector(df, selector), which returns the matched names as a tuple.