polars.struct#

polars.struct(exprs: Union[Sequence[str | polars.internals.expr.expr.Expr | polars.internals.series.series.Series], Expr, Series], eager: Literal[True]) Series[source]#
polars.struct(exprs: Union[Sequence[str | polars.internals.expr.expr.Expr | polars.internals.series.series.Series], Expr, Series], eager: Literal[False]) Expr
polars.struct(exprs: Union[Sequence[str | polars.internals.expr.expr.Expr | polars.internals.series.series.Series], Expr, Series], eager: bool = False) polars.internals.expr.expr.Expr | polars.internals.series.series.Series

Collect several columns into a Series of dtype Struct.

Parameters:
exprs

Columns/Expressions to collect into a Struct

eager

Evaluate immediately

Examples

>>> pl.DataFrame(
...     {
...         "int": [1, 2],
...         "str": ["a", "b"],
...         "bool": [True, None],
...         "list": [[1, 2], [3]],
...     }
... ).select([pl.struct(pl.all()).alias("my_struct")])
shape: (2, 1)
┌─────────────────────┐
│ my_struct           │
│ ---                 │
│ struct[4]           │
╞═════════════════════╡
│ {1,"a",true,[1, 2]} │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ {2,"b",null,[3]}    │
└─────────────────────┘

Only collect specific columns as a struct:

>>> df = pl.DataFrame(
...     {"a": [1, 2, 3, 4], "b": ["one", "two", "three", "four"], "c": [9, 8, 7, 6]}
... )
>>> df.with_column(pl.struct(pl.col(["a", "b"])).alias("a_and_b"))
shape: (4, 4)
┌─────┬───────┬─────┬─────────────┐
│ a   ┆ b     ┆ c   ┆ a_and_b     │
│ --- ┆ ---   ┆ --- ┆ ---         │
│ i64 ┆ str   ┆ i64 ┆ struct[2]   │
╞═════╪═══════╪═════╪═════════════╡
│ 1   ┆ one   ┆ 9   ┆ {1,"one"}   │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ two   ┆ 8   ┆ {2,"two"}   │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ three ┆ 7   ┆ {3,"three"} │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 4   ┆ four  ┆ 6   ┆ {4,"four"}  │
└─────┴───────┴─────┴─────────────┘