
在 Polars 中,可借助 struct + unnest() 机制,仅用一个 when().then().otherwise() 表达式同时生成多个新列,避免重复书写冗余逻辑,显著提升代码简洁性与可维护性。
在 polars 中,可借助 `struct` + `unnest()` 机制,仅用一个 `when().then().otherwise()` 表达式同时生成多个新列,避免重复书写冗余逻辑,显著提升代码简洁性与可维护性。
在数据处理中,我们常需根据相同条件分支为多列赋值(如 Python 中的 if-else 块),若对每列单独写 pl.when(...).then(...).otherwise(...),不仅代码冗长,还易因条件不一致引发逻辑错误。Polars 提供了优雅的解决方案:用 struct 封装多个字段,再通过 .struct.unnest() 一次性展开为独立列。
以下是一个典型示例——根据电影名称 Movie 是否为 "Up",统一为两列 a 和 b 赋值:
import polars as pl
ratings = pl.DataFrame({
"Movie": ["Cars", "IT", "ET", "Cars", "Up", "IT", "Cars", "ET", "Up", "Cars"],
"Theatre": ["NE", "ME", "IL", "ND", "NE", "SD", "NE", "IL", "IL", "NE"],
"Avg_Rating": [4.5, 4.4, 4.6, 4.3, 4.8, 4.7, 4.5, 4.9, 4.7, 4.6],
"Count": [30, 27, 26, 29, 31, 28, 28, 26, 33, 28],
})
result = ratings.with_columns(
pl.when(Movie="Up") # ✅ 支持 kwarg 简写(等价于 pl.col("Movie") == "Up")
.then(pl.struct(a=0, b=2)) # ✅ 字段名直接用关键字参数定义,无需 .alias()
.otherwise(pl.struct(a=1, b=3))
.struct.unnest() # ✅ 一键展开 struct 所有字段为同级列
)
print(result)
输出结果中将新增 a 和 b 两列,且值严格按条件同步分配:
shape: (10, 6) ┌───────┬─────────┬────────────┬───────┬─────┬─────┐ │ Movie ┆ Theatre ┆ Avg_Rating ┆ Count ┆ a ┆ b │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ f64 ┆ i64 ┆ i32 ┆ i32 │ ╞═══════╪═════════╪════════════╪═══════╪═════╪═════╡ │ Cars ┆ NE ┆ 4.5 ┆ 30 ┆ 1 ┆ 3 │ │ IT ┆ ME ┆ 4.4 ┆ 27 ┆ 1 ┆ 3 │ │ ET ┆ IL ┆ 4.6 ┆ 26 ┆ 1 ┆ 3 │ │ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... │ │ Up ┆ NE ┆ 4.8 ┆ 31 ┆ 0 ┆ 2 │ │ Up ┆ IL ┆ 4.7 ┆ 33 ┆ 0 ┆ 2 │ └───────┴─────────┴────────────┴───────┴─────┴─────┘
✅ 关键要点总结:
-
pl.struct(a=0, b=2)比pl.struct(pl.lit(0).alias('a'), pl.lit(2).alias('b'))更简洁,推荐使用关键字参数命名; -
.struct.unnest()是核心——它自动将 struct 的每个字段提升为 DataFrame 的顶层列,无需手动.struct.field(['a','b']); - 若需更多字段(如你的原始需求中的
tot,work,sie,walk),只需扩展 struct 内容即可,例如:otherwise
这一模式大幅提升了 Polars 条件赋值的表达力与工程友好性,是高效构建特征工程流水线的重要技巧。










