polars.struct#
- polars.struct(exprs: IntoExpr | Iterable[IntoExpr] = None, eager: Literal[False] = False, schema: SchemaDict | None = None, **named_exprs: IntoExpr) Expr [source]#
- polars.struct(exprs: IntoExpr | Iterable[IntoExpr] = None, eager: Literal[True] = False, schema: SchemaDict | None = None, **named_exprs: IntoExpr) Series
- polars.struct(exprs: IntoExpr | Iterable[IntoExpr] = None, eager: bool = False, schema: SchemaDict | None = None, **named_exprs: IntoExpr) Expr | Series
Collect columns into a struct column.
- Parameters:
- exprs
Column(s) to collect into a struct column. Accepts expression input. Strings are parsed as column names, other non-expression inputs are parsed as literals.
- eager
Evaluate immediately and return a
Series
. If set toFalse
(default), return an expression instead.- schema
Optional schema that explicitly defines the struct field dtypes.
- **named_exprs
Additional column(s) to collect into the struct column, specified as keyword arguments. The columns will be renamed to the keyword used.
Examples
Collect all columns of a dataframe into a struct by passing
pl.all()
.>>> df = pl.DataFrame( ... { ... "int": [1, 2], ... "str": ["a", "b"], ... "bool": [True, None], ... "list": [[1, 2], [3]], ... } ... ) >>> df.select(pl.struct(pl.all()).alias("my_struct")) shape: (2, 1) ┌─────────────────────┐ │ my_struct │ │ --- │ │ struct[4] │ ╞═════════════════════╡ │ {1,"a",true,[1, 2]} │ │ {2,"b",null,[3]} │ └─────────────────────┘
Collect selected columns into a struct by passing a list of columns.
>>> df.select(pl.struct(["int", False]).alias("my_struct")) shape: (2, 1) ┌───────────┐ │ my_struct │ │ --- │ │ struct[2] │ ╞═══════════╡ │ {1,false} │ │ {2,false} │ └───────────┘
Use keyword arguments to easily name each struct field.
>>> df.select(pl.struct(p="int", q="bool").alias("my_struct")).schema {'my_struct': Struct([Field('p', Int64), Field('q', Boolean)])}