polars.internals.frame.GroupBy.pivot

GroupBy.pivot(pivot_column: Union[str, List[str]], values_column: Union[str, List[str]]) polars.internals.frame.PivotOps[polars.internals.frame.DF]

Do a pivot operation based on the group key, a pivot column and an aggregation function on the values column.

Note

Polars’/arrow memory is not ideal for transposing operations like pivots. If you have a relatively large table, consider using a groupby over a pivot.

Parameters
pivot_column

Column to pivot.

values_column

Column that will be aggregated.

Examples

>>> df = pl.DataFrame(
...     {
...         "foo": ["one", "one", "one", "two", "two", "two"],
...         "bar": ["A", "B", "C", "A", "B", "C"],
...         "baz": [1, 2, 3, 4, 5, 6],
...     }
... )
>>> df.groupby("foo").pivot(pivot_column="bar", values_column="baz").first()
shape: (2, 4)
┌─────┬─────┬─────┬─────┐
│ foo ┆ A   ┆ B   ┆ C   │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╡
│ one ┆ 1   ┆ 2   ┆ 3   │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ two ┆ 4   ┆ 5   ┆ 6   │
└─────┴─────┴─────┴─────┘