polars.DataFrame.pivot#
- DataFrame.pivot(values: Sequence[str] | str, index: Sequence[str] | str, columns: Sequence[str] | str, aggregate_function: PivotAgg | Expr | None | NoDefault = _NoDefault.no_default, *, maintain_order: bool = True, sort_columns: bool = False, separator: str = '_') Self [source]#
Create a spreadsheet-style pivot table as a DataFrame.
- Parameters:
- values
Column values to aggregate. Can be multiple columns if the columns arguments contains multiple columns as well.
- index
One or multiple keys to group by.
- columns
Name of the column(s) whose values will be used as the header of the output DataFrame.
- aggregate_function{‘first’, ‘sum’, ‘max’, ‘min’, ‘mean’, ‘median’, ‘last’, ‘count’}
A predefined aggregate function str or an expression.
- maintain_order
Sort the grouped keys so that the output order is predictable.
- sort_columns
Sort the transposed columns by name. Default is by order of discovery.
- separator
Used as separator/delimiter in generated column names.
- Returns:
- DataFrame
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.pivot(values="baz", index="foo", columns="bar") shape: (2, 4) ┌─────┬─────┬─────┬─────┐ │ foo ┆ A ┆ B ┆ C │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╡ │ one ┆ 1 ┆ 2 ┆ 3 │ │ two ┆ 4 ┆ 5 ┆ 6 │ └─────┴─────┴─────┴─────┘