polars.DataFrame.with_column#

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

Return a new DataFrame with the column added or replaced.

Parameters:
column

Series, where the name of the Series refers to the column in the DataFrame.

Examples

>>> df = pl.DataFrame(
...     {
...         "a": [1, 3, 5],
...         "b": [2, 4, 6],
...     }
... )
>>> df.with_column((pl.col("b") ** 2).alias("b_squared"))  # 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)  # replaced
shape: (3, 2)
┌──────┬─────┐
│ a    ┆ b   │
│ ---  ┆ --- │
│ f64  ┆ i64 │
╞══════╪═════╡
│ 1.0  ┆ 2   │
├╌╌╌╌╌╌┼╌╌╌╌╌┤
│ 9.0  ┆ 4   │
├╌╌╌╌╌╌┼╌╌╌╌╌┤
│ 25.0 ┆ 6   │
└──────┴─────┘