Polars中避免硬编码的.when().then().otherwise()长链替代方案
用Polars动态生成国家参数匹配的列(替代硬编码when-then)
方法1:链式构建条件表达式
先把整个条件逻辑一次性构建完成,再添加到DataFrame,避免重复创建列。
import polars as pl # 你的国家参数字典 country_params = { "US": 30, "CA": 15, "UK": 21, "AU": 28 } # 初始化第一个分支 first_market, first_days = next(iter(country_params.items())) expr = pl.when(pl.col("Market") == first_market).then(first_days) # 遍历剩余参数,拼接when-then分支 for market, days in list(country_params.items())[1:]: expr = expr.when(pl.col("Market") == market).then(days) # 加上默认值并命名新列 expr = expr.otherwise(pl.lit(0)).alias("Number of Days") # 一次性添加到DataFrame df = df.with_columns(expr)
方法2:用map_dict一步搞定(更推荐)
Polars内置的map_dict方法直接实现列值到字典值的映射,代码更简洁,性能也更优:
import polars as pl country_params = { "US": 30, "CA": 15, "UK": 21, "AU": 28 } # 直接生成新列,default指定未匹配到的默认值 df = df.with_columns( pl.col("Market").map_dict(country_params, default=0).alias("Number of Days") )
关于你遇到的重复列名错误
之前循环时出错,大概率是因为你在循环里多次调用with_columns创建同名的"Number of Days"列。正确姿势是先把完整的条件表达式构建好,再一次性调用with_columns添加,避免重复创建列。
内容的提问来源于stack exchange,提问作者miroslaavi
相关产品推荐
相关产品推荐

