polars.internals.dataframe.groupby.GroupBy.pivot#

GroupBy.pivot(pivot_column: str | list[str], values_column: str | list[str]) PivotOps[DF][source]#

Do a pivot operation.

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

Parameters:
pivot_column

Column to pivot.

values_column

Column that will be aggregated.

Notes

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.

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", maintain_order=True).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   │
└─────┴─────┴─────┴─────┘