Skip to content

Polars column selector function namespace

Source code

Description

cs is an environment class object that stores all selector functions of the R Polars API which mimics the Python Polars API. It is intended to work the same way in Python as if you had imported Python Polars Selectors with import polars.selectors as cs.

Usage

cs

selector__as_expr()

Format

An object of class polars_object of length 35.

Supported operators

There are 4 supported operators for selectors:

  • & to combine conditions with AND, e.g. select columns that contain “oo” and end with “t” with cs$contains(“oo”) & cs$ends_with(“t”);
  • | to combine conditions with OR, e.g. select columns that contain “oo” or end with “t” with cs$contains(“oo”) | cs$ends_with(“t”);
  • - to substract conditions, e.g. select all columns that have alphanumeric names except those that contain “a” with cs$alphanumeric() - cs$contains(“a”);
  • ! to invert the selection, e.g. select all columns that are not of data type String with !cs$string().

Note that Python Polars uses ~ instead of ! to invert selectors.

If we want to apply operators on the data instead of the selector sets, \<selector>$as_expr() can be used to materialize the selector as a normal expression.

Examples

library("polars")

cs
#> <polars_object>
df <- pl$DataFrame(
  colx = c("aa", "bb", "cc"),
  coly = c(TRUE, FALSE, TRUE),
  colz = c(1, 2, 3),
)

# Inverting the boolean selector will choose the non-boolean columns:
df$select(!cs$boolean())
#> shape: (3, 2)
#> ┌──────┬──────┐
#> │ colx ┆ colz │
#> │ ---  ┆ ---  │
#> │ str  ┆ f64  │
#> ╞══════╪══════╡
#> │ aa   ┆ 1.0  │
#> │ bb   ┆ 2.0  │
#> │ cc   ┆ 3.0  │
#> └──────┴──────┘
# To invert the values in the selected boolean columns,
# we need to materialize the selector as a standard expression instead:
df$select(!cs$boolean()$as_expr())
#> shape: (3, 1)
#> ┌───────┐
#> │ coly  │
#> │ ---   │
#> │ bool  │
#> ╞═══════╡
#> │ false │
#> │ true  │
#> │ false │
#> └───────┘