pandasdataframepython-polarssetvalue

How to update a single value in Polars dataframe?


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?


Solution

  • 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   │
    └──────┴──────┘