polars pivot for dataframe
Pivot a DataFrame from long to wide format.
Signature
> polars pivot {flags}
Flags
--on, -o {list<string>}: Column names for pivoting.--index, -i {list<string>}: Column names for indexes.--values, -v {list<string>}: Column names used as value columns.--aggregate, -a {any}: Aggregation to apply when pivoting. The following are supported: first, sum, min, max, mean, median, count, last, or a custom expression.--separator, -p {string}: Delimiter in generated column names in case of multiplevaluescolumns (default '_').--sort, -s: Sort columns.--streamable, -t: Whether or not to use the polars streaming engine. Only valid for lazy dataframes.--stable: Perform a stable pivot.
Input/output types:
| input | output |
|---|---|
| polars_dataframe | polars_dataframe |
| polars_lazyframe | polars_lazyframe |
Examples
Perform a pivot in order to show individuals test score by subject
> [[name subject date test_1 test_2]; [Cady maths 2025-04-01 98 100] [Cady physics 2025-04-01 99 100] [Karen maths 2025-04-02 61 60] [Karen physics 2025-04-02 58 60]] | polars into-df | polars pivot --on [subject] --index [name date] --values [test_1]
╭───┬───────┬───────────────┬───────┬─────────╮
│ # │ name │ date │ maths │ physics │
├───┼───────┼───────────────┼───────┼─────────┤
│ 0 │ Cady │ 11 months ago │ 98 │ 99 │
│ 1 │ Karen │ 11 months ago │ 61 │ 58 │
╰───┴───────┴───────────────┴───────┴─────────╯Perform a pivot with multiple values columns with a separator
> [[name subject date test_1 test_2 grade_1 grade_2]; [Cady maths 2025-04-01 98 100 A A] [Cady physics 2025-04-01 99 100 A A] [Karen maths 2025-04-02 61 60 D D] [Karen physics 2025-04-02 58 60 D D]] | polars into-df | polars pivot --on [subject] --index [name] --values [test_1 grade_1] --separator /
╭───┬───────┬──────────────┬────────────────┬───────────────┬─────────────────╮
│ # │ name │ test_1/maths │ test_1/physics │ grade_1/maths │ grade_1/physics │
├───┼───────┼──────────────┼────────────────┼───────────────┼─────────────────┤
│ 0 │ Cady │ 98 │ 99 │ A │ A │
│ 1 │ Karen │ 61 │ 58 │ D │ D │
╰───┴───────┴──────────────┴────────────────┴───────────────┴─────────────────╯