I would like to add new column using other column value with condition
In pandas, I do this like below
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
df['c'] = df['a']
df.loc[df['b']==4, 'c'] = df['b']
The result is
a | b | c |
---|---|---|
1 | 3 | 1 |
2 | 4 | 4 |
Could you teach me how to do this with polars?
CodePudding user response:
try this
df["c"] = df.apply(lambda x: 4 if x["b"]==4 else x["a"], axis=1)
CodePudding user response:
df = pl.DataFrame({'a': [1, 2], 'b': [3, 4]})
df.with_columns(
pl.when(pl.col("b") == 4).then(pl.col('b')).otherwise(pl.col('a')).alias("c")
)