polars.Expr.to_physical#

Expr.to_physical() Expr[source]#

Cast to physical representation of the logical dtype.

Examples

Replicating the pandas pd.factorize function.

>>> pl.DataFrame({"vals": ["a", "x", None, "a"]}).with_columns(
...     [
...         pl.col("vals").cast(pl.Categorical),
...         pl.col("vals")
...         .cast(pl.Categorical)
...         .to_physical()
...         .alias("vals_physical"),
...     ]
... )
shape: (4, 2)
┌──────┬───────────────┐
│ vals ┆ vals_physical │
│ ---  ┆ ---           │
│ cat  ┆ u32           │
╞══════╪═══════════════╡
│ a    ┆ 0             │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ x    ┆ 1             │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ null ┆ null          │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ a    ┆ 0             │
└──────┴───────────────┘