Inset value in polars dataframe

Hi

I have a polars dataframe where I need to update values in a column where the rows corresponds to a column called ID (type str). Kind of like this quasi code:
if row fulfills ID = ‘string’ update a float value in column ‘columnname’

I’m fairly new to polars dataframe and can’t get it to work.

I think you need something in the direction of

df=df.with_column(pl.col('name').where(id==Val).then(new).else(old))

Thanks

Your reply is confusing to me… Isn’t with_column for adding a column to the dataframe? Isn’t there some way of updating a single row column, i.e. a single cell. I couldn’t get you code working.

No, you can use with_column to overwrite a column, if you specify a column that has the same name as a column you already have.

You need a polars.when().then().otherwise() structure. Which was the very first thing on top of my google results when I searched for “polars where then else”.

https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.when.html

It genuinly is hard to get polars to work when you’re starting out. The expressions are tricky. Sometimes AI chatbots help.

Okay thanks!

Now I’m able to update values. However, when I try to repeat and update more values after the first update previously updated values are changed to the original values.

name = 'Column2'
String1 = 'STR1'
new_df = new_df.with_columns(pl.when(pl.col('ID') == String1).then(1).alias(name))


String2 = 'STR2'

new_df = new_df.with_columns(pl.when(pl.col('ID') == String2).then(2).alias(name))
print(new_df)

EDIT: I have another question linked to this. I use this to add a column, which should be a float, but is a i32. Could that be the reason why i fail…?

df.with_columns(name = pl.lit(None))

I think my approach was wrong. I was able to do what I wanted to do by first creating a dict with key and value and form a dataframe from the dict. Then I could join the two dataframes of key.