Skip to content

Retrieve one or multiple Struct field(s) as a new Series

Description

Retrieve one or multiple Struct field(s) as a new Series

Usage

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

Arguments

\<dynamic-dots\> Names of struct fields to retrieve.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(
  aaa = c(1, 2),
  bbb = c("ab", "cd"),
  ccc = c(TRUE, NA),
  ddd = list(1:2, 3)
)$select(struct_col = pl$struct("aaa", "bbb", "ccc", "ddd"))
df
#> shape: (2, 1)
#> ┌────────────────────────────┐
#> │ struct_col                 │
#> │ ---                        │
#> │ struct[4]                  │
#> ╞════════════════════════════╡
#> │ {1.0,"ab",true,[1.0, 2.0]} │
#> │ {2.0,"cd",null,[3.0]}      │
#> └────────────────────────────┘
# Retrieve struct field(s) as Series:
df$select(pl$col("struct_col")$struct$field("bbb"))
#> shape: (2, 1)
#> ┌─────┐
#> │ bbb │
#> │ --- │
#> │ str │
#> ╞═════╡
#> │ ab  │
#> │ cd  │
#> └─────┘
df$select(
  pl$col("struct_col")$struct$field("bbb"),
  pl$col("struct_col")$struct$field("ddd")
)
#> shape: (2, 2)
#> ┌─────┬────────────┐
#> │ bbb ┆ ddd        │
#> │ --- ┆ ---        │
#> │ str ┆ list[f64]  │
#> ╞═════╪════════════╡
#> │ ab  ┆ [1.0, 2.0] │
#> │ cd  ┆ [3.0]      │
#> └─────┴────────────┘
# Use wildcard expansion:
df$select(pl$col("struct_col")$struct$field("*"))
#> shape: (2, 4)
#> ┌─────┬─────┬──────┬────────────┐
#> │ aaa ┆ bbb ┆ ccc  ┆ ddd        │
#> │ --- ┆ --- ┆ ---  ┆ ---        │
#> │ f64 ┆ str ┆ bool ┆ list[f64]  │
#> ╞═════╪═════╪══════╪════════════╡
#> │ 1.0 ┆ ab  ┆ true ┆ [1.0, 2.0] │
#> │ 2.0 ┆ cd  ┆ null ┆ [3.0]      │
#> └─────┴─────┴──────┴────────────┘
# Retrieve multiple fields by name:
df$select(pl$col("struct_col")$struct$field("aaa", "bbb"))
#> shape: (2, 2)
#> ┌─────┬─────┐
#> │ aaa ┆ bbb │
#> │ --- ┆ --- │
#> │ f64 ┆ str │
#> ╞═════╪═════╡
#> │ 1.0 ┆ ab  │
#> │ 2.0 ┆ cd  │
#> └─────┴─────┘
# Retrieve multiple fields by regex expansion:
df$select(pl$col("struct_col")$struct$field("^a.*|b.*$"))
#> shape: (2, 2)
#> ┌─────┬─────┐
#> │ aaa ┆ bbb │
#> │ --- ┆ --- │
#> │ f64 ┆ str │
#> ╞═════╪═════╡
#> │ 1.0 ┆ ab  │
#> │ 2.0 ┆ cd  │
#> └─────┴─────┘