Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polars: how to add a column in front? [duplicate]

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?

like image 889
loxs Avatar asked Nov 02 '25 03:11

loxs


1 Answers

You can select in the order you want your new DataFrame.

df = pl.DataFrame({
    "a": [1, 2, 3],
    "b": [True, None, False]
})

df.select(
    pl.lit("foo").alias("z"),
    pl.all()
)
shape: (3, 3)
┌─────┬─────┬───────┐
│ z   ┆ a   ┆ b     │
│ --- ┆ --- ┆ ---   │
│ str ┆ i64 ┆ bool  │
╞═════╪═════╪═══════╡
│ foo ┆ 1   ┆ true  │
│ foo ┆ 2   ┆ null  │
│ foo ┆ 3   ┆ false │
└─────┴─────┴───────┘

like image 195
ritchie46 Avatar answered Nov 03 '25 16:11

ritchie46



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!