polars.DataFrame.insert_column#

DataFrame.insert_column(index: int, column: IntoExprColumn) DataFrame[source]#

Insert a Series (or expression) at a certain column index.

This operation is in place.

Parameters:
index

Index at which to insert the new column.

column

Series or expression to insert.

Examples

Insert a new Series column at the given index:

>>> df = pl.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
>>> s = pl.Series("baz", [97, 98, 99])
>>> df.insert_column(1, s)
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ baz ┆ bar │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1   ┆ 97  ┆ 4   │
│ 2   ┆ 98  ┆ 5   │
│ 3   ┆ 99  ┆ 6   │
└─────┴─────┴─────┘

Insert a new expression column at the given index:

>>> df = pl.DataFrame(
...     {"a": [2, 4, 2], "b": [0.5, 4, 10], "c": ["xx", "yy", "zz"]}
... )
>>> expr = (pl.col("b") / pl.col("a")).alias("b_div_a")
>>> df.insert_column(2, expr)
shape: (3, 4)
┌─────┬──────┬─────────┬─────┐
│ a   ┆ b    ┆ b_div_a ┆ c   │
│ --- ┆ ---  ┆ ---     ┆ --- │
│ i64 ┆ f64  ┆ f64     ┆ str │
╞═════╪══════╪═════════╪═════╡
│ 2   ┆ 0.5  ┆ 0.25    ┆ xx  │
│ 4   ┆ 4.0  ┆ 1.0     ┆ yy  │
│ 2   ┆ 10.0 ┆ 5.0     ┆ zz  │
└─────┴──────┴─────────┴─────┘