polars unpivot
For dataframe.
Unpivot a DataFrame from wide to long format.
warning This command requires a plugin The
polars unpivotcommand resides in thepolarsplugin. To use this command, you must install and registernu_plugin_polars. See the Plugins chapter in the book for more information.
Command Type
plugin
Signature
> polars unpivot {flags}
Flags
--index, -i {list<any>}: Column names for unpivoting.--on, -o {list<any>}: Column names used as value columns.--variable-name, -r {string}: Optional name for variable column.--value-name, -l {string}: Optional name for value column.
Input/output types:
| input | output |
|---|---|
| polars_dataframe | polars_dataframe |
| polars_lazyframe | polars_lazyframe |
Examples
unpivot on an eager dataframe
> [[a b c d]; [x 1 4 a] [y 2 5 b] [z 3 6 c]] | polars into-df | polars unpivot -i [b c] -o [a d]
╭───┬───┬───┬──────────┬───────╮
│ # │ b │ c │ variable │ value │
├───┼───┼───┼──────────┼───────┤
│ 0 │ 1 │ 4 │ a │ x │
│ 1 │ 2 │ 5 │ a │ y │
│ 2 │ 3 │ 6 │ a │ z │
│ 3 │ 1 │ 4 │ d │ a │
│ 4 │ 2 │ 5 │ d │ b │
│ 5 │ 3 │ 6 │ d │ c │
╰───┴───┴───┴──────────┴───────╯
unpivot on a lazy dataframe
> [[a b c d]; [x 1 4 a] [y 2 5 b] [z 3 6 c]] | polars into-lazy | polars unpivot -i [b c] -o [a d] | polars collect
╭───┬───┬───┬──────────┬───────╮
│ # │ b │ c │ variable │ value │
├───┼───┼───┼──────────┼───────┤
│ 0 │ 1 │ 4 │ a │ x │
│ 1 │ 2 │ 5 │ a │ y │
│ 2 │ 3 │ 6 │ a │ z │
│ 3 │ 1 │ 4 │ d │ a │
│ 4 │ 2 │ 5 │ d │ b │
│ 5 │ 3 │ 6 │ d │ c │
╰───┴───┴───┴──────────┴───────╯
Ported from nushell/nushell.github.io. Copyright (c) 2021 Nushell Project. MIT License.