Joseph K
Joseph K

Reputation: 67

Creating new polars dataframe column based on other column

I have a hard time with what should be a very common use case on polars dataframes. I simply want to create a new column on an existing dataframe based on some other column. Here is the code I try, but doesn't work:

import polars as pl
df.with_columns(
                (pl.col('old_col').map_elements(lambda x: func(x)).alias("new_col"),
            )

Upvotes: 2

Views: 1946

Answers (1)

ritchie46
ritchie46

Reputation: 14710

Polars uses pure functions meaning that they don't have any side effects nor mutably change self.

This property will ensure that you can safely pass a DataFrame to another function without being afraid that that function changes the state of the DataFrame underneath of you.

If you want to change the assigned variable, simply reassign the new state:

df = df.with_columns(...)

Upvotes: 3

Related Questions