polars with-column

For [dataframe or lazyframe](/commands/categories/dataframe or lazyframe.md).

Adds a series to the dataframe.

warning This command requires a plugin The polars with-column 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.

Command Type

plugin

Signature

> polars with-column {flags} ...rest

Flags

  • --name, -n {string}: New column name. For lazy dataframes and expressions syntax, use a polars as expression to name a column.

Parameters

  • ...rest: Series to be added or expressions used to define the new columns.

Input/output types:

input output
polars_dataframe polars_dataframe
polars_lazyframe polars_lazyframe

Examples

Adds a series to the dataframe

> [[a b]; [1 2] [3 4]]
    | polars into-df
    | polars with-column ([5 6] | polars into-df) --name c
╭───┬───┬───┬───╮
│ # │ a │ b │ c │
├───┼───┼───┼───┤
│ 0 │ 1 │ 2 │ 5 │
│ 1 │ 3 │ 4 │ 6 │
╰───┴───┴───┴───╯

Adds a series to the dataframe

> [[a b]; [1 2] [3 4]]
    | polars into-lazy
    | polars with-column [
        ((polars col a) * 2 | polars as "c")
        ((polars col a) * 3 | polars as "d")
      ]
    | polars collect
╭───┬───┬───┬───┬───╮
│ # │ a │ b │ c │ d │
├───┼───┼───┼───┼───┤
│ 0 │ 1 │ 2 │ 2 │ 3 │
│ 1 │ 3 │ 4 │ 6 │ 9 │
╰───┴───┴───┴───┴───╯

Add series to a lazyframe using a record

> [[a b]; [1 2] [3 4]]
    | polars into-lazy
    | polars with-column {
        c: ((polars col a) * 2)
        d: ((polars col a) * 3)
      }
    | polars collect
╭───┬───┬───┬───┬───╮
│ # │ a │ b │ c │ d │
├───┼───┼───┼───┼───┤
│ 0 │ 1 │ 2 │ 2 │ 3 │
│ 1 │ 3 │ 4 │ 6 │ 9 │
╰───┴───┴───┴───┴───╯

Add series to a dataframe using a record

> [[a b]; [1 2] [3 4]]
    | polars into-df
    | polars with-column {
        c: ((polars col a) * 2)
        d: ((polars col a) * 3)
      }
    | polars collect
╭───┬───┬───┬───┬───╮
│ # │ a │ b │ c │ d │
├───┼───┼───┼───┼───┤
│ 0 │ 1 │ 2 │ 2 │ 3 │
│ 1 │ 3 │ 4 │ 6 │ 9 │
╰───┴───┴───┴───┴───╯

Add columns using a selector to multiply all columns by 2

> [[a b]; [1 2] [3 4]]
    | polars into-df
    | polars with-column ((polars selector all) * 2)
    | polars collect
╭───┬───┬───╮
│ # │ a │ b │
├───┼───┼───┤
│ 0 │ 2 │ 4 │
│ 1 │ 6 │ 8 │
╰───┴───┴───╯

Add a new column using a selector on the first column

> [[a b c]; [1 2 3] [4 5 6]]
    | polars into-df
    | polars with-column ((polars selector first) * 10 | polars as a_times_10)
    | polars collect
╭───┬───┬───┬───┬────────────╮
│ # │ a │ b │ c │ a_times_10 │
├───┼───┼───┼───┼────────────┤
│ 0 │ 1 │ 2 │ 3 │         10 │
│ 1 │ 4 │ 5 │ 6 │         40 │
╰───┴───┴───┴───┴────────────╯

Ported from nushell/nushell.github.io. Copyright (c) 2021 Nushell Project. MIT License.