polars.Expr.keep_name#

Expr.keep_name() Expr[source]#

Keep the original root name of the expression.

Examples

A groupby aggregation often changes the name of a column. With keep_name we can keep the original name of the column

>>> df = pl.DataFrame(
...     {
...         "a": [1, 2, 3],
...         "b": ["a", "b", None],
...     }
... )
>>> df.groupby("a").agg(pl.col("b").list()).sort(by="a")
shape: (3, 2)
┌─────┬───────────┐
│ a   ┆ b         │
│ --- ┆ ---       │
│ i64 ┆ list[str] │
╞═════╪═══════════╡
│ 1   ┆ ["a"]     │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ ["b"]     │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ [null]    │
└─────┴───────────┘

Keep the original column name:

>>> df.groupby("a").agg(pl.col("b").list().keep_name()).sort(by="a")
shape: (3, 2)
┌─────┬───────────┐
│ a   ┆ b         │
│ --- ┆ ---       │
│ i64 ┆ list[str] │
╞═════╪═══════════╡
│ 1   ┆ ["a"]     │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ ["b"]     │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ [null]    │
└─────┴───────────┘