Search code examples
python-polars

Polars: how to add a column in front?


What would be the most idiomatic (and efficient) way to add a column in front of a polars data frame? Same thing like .with_columns but add it at index 0?


Solution

  • Since version 1.9.0 you can do it with pl.DataFrame.insert_column() which supports expression now, which can refer to existing columns as well:

    df = pl.DataFrame({
        "a":[1,2,3],
        "b": list("abc")
    })
    
    
    df.insert_column(
        0,
        (pl.col.a + 1).alias("c")
    )
    
    shape: (3, 3)
    ┌─────┬─────┬─────┐
    │ c   ┆ a   ┆ b   │
    │ --- ┆ --- ┆ --- │
    │ i64 ┆ i64 ┆ str │
    ╞═════╪═════╪═════╡
    │ 2   ┆ 1   ┆ a   │
    │ 3   ┆ 2   ┆ b   │
    │ 4   ┆ 3   ┆ c   │
    └─────┴─────┴─────┘