How to update a single value in Polars dataframe?

870 Views Asked by At

In Pandas, you can update a value with the at property, like this:

import pandas as pd

df = pd.DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]})
df.at[2, "col2"] = 99

print(df)
# Output

   col1  col2
0     1     4
1     2     5
2     3    99

What's the idiomatic way to do that in Polars?

2

There are 2 best solutions below

0
Timeless On BEST ANSWER

You can use polars' square brackets indexing :

df = pl.DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]})
​
df[2, "col2"] = 99 #same syntax as pandas but without the `.at`

​ Output :

print(df)
​
shape: (3, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ ---  ┆ ---  │
│ i64  ┆ i64  │
╞══════╪══════╡
│ 1    ┆ 4    │
│ 2    ┆ 5    │
│ 3    ┆ 99   │
└──────┴──────┘
0
ignoring_gravity On

You can use when-then-otherwise:

df.with_row_count().with_columns(
    col2=pl.when(pl.col("row_nr") == 2)
    .then(99)
    .otherwise(pl.col("col2"))
).drop("row_nr")

example:

In [5]: df.with_row_count().with_columns(col2=pl.when(pl.col('row_nr')==2).then(99).otherwise(pl.col('col2'))).drop('row_nr')
Out[5]:
shape: (3, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ ---  ┆ ---  │
│ i64  ┆ i64  │
╞══════╪══════╡
│ 1    ┆ 4    │
│ 2    ┆ 5    │
│ 3    ┆ 99   │
└──────┴──────┘

It does seem a bit verbose though, so I'm curious if other answers will suggest something simpler