Quickly select a field in a Struct
Description
This is syntactic sugar that should mostly be used in
$struct$with_fields()
. pl$field(“x”)
is
equivalent to pl$col(“my_struct”)$struct$field(“x”)
.
Usage
pl$field(name)
Arguments
name
|
Name of the field to select. |
Value
An Expr with the datatype from the selected field.
Examples
library("polars")
df = pl$DataFrame(x = c(1, 4, 9), y = c(4, 9, 16), multiply = c(10, 2, 3))$
with_columns(coords = pl$struct(c("x", "y")))$
select("coords", "multiply")
df
#> shape: (3, 2)
#> ┌────────────┬──────────┐
#> │ coords ┆ multiply │
#> │ --- ┆ --- │
#> │ struct[2] ┆ f64 │
#> ╞════════════╪══════════╡
#> │ {1.0,4.0} ┆ 10.0 │
#> │ {4.0,9.0} ┆ 2.0 │
#> │ {9.0,16.0} ┆ 3.0 │
#> └────────────┴──────────┘
df = df$with_columns(
pl$col("coords")$struct$with_fields(
pl$field("x")$sqrt(),
y_mul = pl$field("y") * pl$col("multiply")
)
)
df
#> shape: (3, 2)
#> ┌─────────────────┬──────────┐
#> │ coords ┆ multiply │
#> │ --- ┆ --- │
#> │ struct[3] ┆ f64 │
#> ╞═════════════════╪══════════╡
#> │ {1.0,4.0,40.0} ┆ 10.0 │
#> │ {2.0,9.0,18.0} ┆ 2.0 │
#> │ {3.0,16.0,48.0} ┆ 3.0 │
#> └─────────────────┴──────────┘
#> shape: (3, 4)
#> ┌─────┬──────┬───────┬──────────┐
#> │ x ┆ y ┆ y_mul ┆ multiply │
#> │ --- ┆ --- ┆ --- ┆ --- │
#> │ f64 ┆ f64 ┆ f64 ┆ f64 │
#> ╞═════╪══════╪═══════╪══════════╡
#> │ 1.0 ┆ 4.0 ┆ 40.0 ┆ 10.0 │
#> │ 2.0 ┆ 9.0 ┆ 18.0 ┆ 2.0 │
#> │ 3.0 ┆ 16.0 ┆ 48.0 ┆ 3.0 │
#> └─────┴──────┴───────┴──────────┘