Skip to content

Add or overwrite fields of this struct

Source code

Description

This is similar to $with_columns() on DataFrame. Use pl$field() to quickly select a field in a $struct$with_fields() context.

Usage

<Expr>$struct$with_fields(...)

Arguments

Field(s) to add. Accepts expression input. Strings are parsed as column names, other non-expression inputs are parsed as literals.

Value

An Expr of data type Struct.

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      │
#> └─────────────────┴──────────┘
df$unnest("coords")
#> 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      │
#> └─────┴──────┴───────┴──────────┘