polars.LazyFrame.with_column#

LazyFrame.with_column(column: Series | Expr) LDF[source]#

Add or overwrite column in a DataFrame.

Parameters:
column

Expression that evaluates to column or a Series to use.

Examples

>>> df = pl.DataFrame(
...     {
...         "a": [1, 3, 5],
...         "b": [2, 4, 6],
...     }
... ).lazy()
>>> df.with_column((pl.col("b") ** 2).alias("b_squared")).collect()  # added
shape: (3, 3)
┌─────┬─────┬───────────┐
│ a   ┆ b   ┆ b_squared │
│ --- ┆ --- ┆ ---       │
│ i64 ┆ i64 ┆ f64       │
╞═════╪═════╪═══════════╡
│ 1   ┆ 2   ┆ 4.0       │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ 4   ┆ 16.0      │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 5   ┆ 6   ┆ 36.0      │
└─────┴─────┴───────────┘
>>> df.with_column(pl.col("a") ** 2).collect()  # replaced
shape: (3, 2)
┌──────┬─────┐
│ a    ┆ b   │
│ ---  ┆ --- │
│ f64  ┆ i64 │
╞══════╪═════╡
│ 1.0  ┆ 2   │
├╌╌╌╌╌╌┼╌╌╌╌╌┤
│ 9.0  ┆ 4   │
├╌╌╌╌╌╌┼╌╌╌╌╌┤
│ 25.0 ┆ 6   │
└──────┴─────┘
>>> df.with_column(pl.Series("c", [7, 8, 9])).collect()  # add from a Series
shape: (3, 3)
┌─────┬─────┬─────┐
│ a   ┆ b   ┆ c   │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1   ┆ 2   ┆ 7   │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 3   ┆ 4   ┆ 8   │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 5   ┆ 6   ┆ 9   │
└─────┴─────┴─────┘