Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Polars · Module

df.pivot

Creates a spreadsheet-style pivot table in eager mode, turning values from on into columns and retaining index keys as rows. Use aggregate_function when an index/on group can contain multiple values.

How it works

In eager mode, pivot groups rows by index columns, turns distinct values from on into output columns, and places values into those columns. If combinations can produce multiple rows, aggregate_function resolves them; optional settings control ordering, generated-name separators, and multi-value column naming.

Syntax

DataFrame.pivot(on, on_columns=None, *, index=None, values=None, aggregate_function=None, maintain_order=True, sort_columns=False, separator='_', column_naming='auto')

Parameters

NameTypeDescription
onColumnNameOrSelector | Sequence[ColumnNameOrSelector]Column name(s) or selectors whose values become output columns.
on_columnsSequence[Any] | Series | DataFrame | NoneValue combinations considered for the output table.
indexColumnNameOrSelector | Sequence[ColumnNameOrSelector] | NoneColumn name(s) or selectors retained as row identifiers; each unique combination forms one output row.
valuesColumnNameOrSelector | Sequence[ColumnNameOrSelector] | NoneColumn name(s) or selectors whose data is placed under generated columns.
aggregate_functionPivotAgg | Expr | NoneAggregation name or expression used when groups contain multiple values.
maintain_orderbool = TrueWhether grouped-key order is maintained.
sort_columnsbool = FalseWhether generated pivot columns are sorted by name.
separatorstr = '_'Delimiter used in generated column names.
column_namingLiteral['auto', 'combine'] = 'auto'Naming mode for multiple value columns.

Returns

DataFrame

Key points

  • The method converts long-form records into a spreadsheet-like wide table.
  • on determines which input column values become the output columns.
  • index columns define the identifying fields retained in the result.
  • values supplies the measurements relocated beneath the generated pivot columns.
  • sort_columns=True alphabetizes the generated pivot columns instead of using discovery order.
  • on_columns can explicitly provide the value combinations considered when constructing output columns.

Common mistakes

  • DataFrame.pivot cannot be used directly as a lazy operation; materialize the LazyFrame before pivoting.
  • Provide at least one grouping column or value column; omitting both is invalid.
  • With aggregate_function=None, duplicate index/on combinations raise an error instead of being reduced.

Example: Pivot long data to wide form

import polars as pl

df = pl.DataFrame({
    "group": ["a", "a", "b"],
    "kind": ["x", "y", "x"],
    "value": [1, 2, 3],
})

result = df.pivot(
    on="kind",
    index="group",
    values="value",
    aggregate_function="sum",
)
print(result)

Creates one row per group and one output column per kind, summing values where combinations repeat.

When to use it

Long-to-wide reshaping

Convert event or transaction records with category labels into one row per entity and one column per category.

Grouped aggregation

Summarize repeated entity/category combinations using sum, mean, or another aggregation.

Reporting tables

Create a report-friendly table whose headers are discovered from categorical data.

Interview questions

QWhat does DataFrame.pivot do?

It reshapes a DataFrame into a spreadsheet-style table. Values from on become output columns, index identifies output rows, and values supplies the data placed under those columns.

Follow-up: Why is it eager-only? The generated column names depend on data values, so the schema cannot be known in advance during lazy planning.

QHow are duplicate pivot groups handled?

aggregate_function resolves multiple input rows that map to the same index/on combination. It can be a supported aggregation name such as sum, mean, first, or len, or an expression.

Follow-up: What happens if it is None? No reduction occurs, and multiple values in one group cause an error.

QWhich options affect output ordering and names?

maintain_order defaults to True and preserves predictable grouped-key order. sort_columns defaults to False, so transposed columns remain in discovery order rather than being alphabetically sorted.

Follow-up: How can generated names be controlled? separator changes delimiters, while column_naming supports auto or combine naming for multiple value columns.

  • polars.DataFrame.unpivot
  • polars.LazyFrame.pivot

Source: polars.DataFrame.pivot — Polars documentation. Checked 2026-10-15.