polars pivot
for dataframe
Pivot a DataFrame from long to wide format.
This command requires a plugin
The polars pivot
command resides in the polars
plugin. To use this command, you must install and register nu_plugin_polars
. See the Plugins chapter in the book for more information.
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 {string}
: Aggregation to apply when pivoting. The following are supported: first, sum, min, max, mean, median, count, last--separator, -p {string}
: Delimiter in generated column names in case of multiplevalues
columns (default '_')--sort, -s
: Sort columns--streamable, -t
: Whether or not to use the polars streaming engine. Only valid for lazy dataframes
Input/output types:
input | output |
---|---|
any | any |
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 │ 4 weeks ago │ 98 │ 99 │
│ 1 │ Karen │ 3 weeks 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 │
╰───┴───────┴──────────────┴────────────────┴───────────────┴─────────────────╯