Skip to content

Guides

Selections

A selector picks columns by name or by data type, for example cs.numeric(). A selection is a selector with operations after it, for example cs.numeric().round(2). The type of a selection carries the selector, one result for each data type that it picks, and a rename. So an operation applies it to the declared columns and to the remainder alike.

typed_selection(selector, gives=) declares a selection. gives=same keeps the data type of each column:

selections.pymypy: no errors
1class Trades(Columns):
2 symbol: pl.String
3 price: pl.Float64
4 quantity: pl.Int64
5
6
7trades: TypedDataFrame[Trades]
8Rounded = typed_selection(cs.numeric(), gives=same)
9
10
11def rounded(columns: Rounded) -> Rounded:
12 return columns.round(2)
13
14
15tidy = trades.with_columns(rounded(cs.numeric()))
Resulttidydeclared
symbolStringpriceFloat64quantityInt64
Revealed type
TypedDataFrame[TypedDict(Trades, {'symbol': String, 'price': Float64, 'quantity': Int64}, closed=True), None]

typed_agg_selection(...) declares a selection that gives one value for each group, for example cs.numeric().sum(). Where the result depends on the data type of a column, give row(...) parts in place of gives=.

A selection gives one column for each column that it picks. .name.suffix() and .name.prefix() keep different names different:

selections.pymypy: 1 error
1class Trades(Columns):
2 symbol: pl.String
3 price: pl.Float64
4 quantity: pl.Int64
5
6
7trades: TypedDataFrame[Trades]
8doubled = trades.with_columns((cs.numeric() * 2).name.suffix("_x2"))
9trades.select(cs.numeric().alias("number"))
error: A selection has several outputs, which .alias() cannot rename: use .name.suffix() or .name.prefix() [selection-rename]
Resultdoubleddeclaredadded
symbolStringpriceFloat64quantityInt64price_x2Float64quantity_x2Int64
Revealed type
TypedDataFrame[TypedDict({'symbol': String, 'price': Float64, 'quantity': Int64, 'price_x2': Float64, 'quantity_x2': Int64}, closed=True), None]

.alias() cannot name several columns, so it is an error on a selection that picks several columns. A rewrite of each whole name, for example .name.to_lowercase(), applies to each picked column. If it turns two names into one, the checker reports [duplicate-column], because Polars refuses two columns with one name.

A selection can read other columns: cs.numeric() + pl.col("fee") adds fee to each picked column, and cs.numeric().sum().over("desk") sums each one by desk. The frame must declare fee and desk.

.struct.unnest() spreads the fields of a struct expression, and .name.keep() gives an expression back the name of its first column.