Are there some clever alternatives writing long when().then().otherwise() chains without hardcoding the values, see the example below:
Let's say we have the following dataframe
df = pl.DataFrame(
{
"Market":["AT", "AT", "DE", "DE", "CA", "DE", "UK", "US"],
"Number of Days":[1, 2, 3, 4, 3, 4, 2, 1],
}
)
User defines some conditions as a dictionary for different countries
params = {
"AT":{"Value": 1},
"DE":{"Value": 2},
"CA":{"Value": 3},
"UK":{"Value": 1},
"US":{"Value": 2}
}
Then I hard-code the countries and use the countries in the Polars .with_columns() as below:
(
df
.with_columns(
[
pl.when(pl.col("Market") == "AT").then(pl.col("Number of Days") + params["AT"]["Value"])
.when(pl.col("Market") == "DE").then(pl.col("Number of Days") + params["DE"]["Value"])
.when(pl.col("Market") == "CA").then(pl.col("Number of Days") + params["CA"]["Value"])
.when(pl.col("Market") == "UK").then(pl.col("Number of Days") + params["UK"]["Value"])
.when(pl.col("Market") == "US").then(pl.col("Number of Days") + params["US"]["Value"])
.otherwise(None)
.alias("New Column")
]
)
)
Is there a way for me not to hard-code the countries in .with_columns, but somehow loop through the dictionary and create expression based on the values provided?¨
I tried the below but it says I have duplicate column names.
exprs = []
for market, data in params.items():
condition = (pl.col("Market") == market)
result = (pl.col("Number of Days") + data["Value"])
expr = pl.when(condition).then(result)
exprs.append(expr)
df.with_columns(exprs)