
Polars 支持通过 struct + when/then/otherwise 结合 .struct.unnest(),仅用一次条件判断批量生成多个新列,避免重复书写冗余逻辑,显著提升代码简洁性与可维护性。
polars 支持通过 `struct` + `when/then/otherwise` 结合 `.struct.unnest()`,仅用一次条件判断批量生成多个新列,避免重复书写冗余逻辑,显著提升代码简洁性与可维护性。
在数据处理中,常需根据相同条件为多列赋值(如 Python 中的 if-else 块同时设置 tot, work, sie, walk)。若在 Polars 中为每个变量单独写 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') # ✅ 支持关键字参数简写(等价于 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 的顶层列,无需手动.field('a').field('b'); - 若需扩展至 4 列(如
tot,work,sie,walk),只需在pl.struct()中添加对应键值对(支持混合类型,如字符串'into'与数值300); - ⚠️ 注意:
pl.struct()中所有字段必须显式命名(不能依赖默认名),否则.unnest()会报DuplicateError; - 条件复杂时(如原文中的
x==1 and y==3 and w==300*z and z),可组合 <code>&运算符:pl.when((pl.col('x')==1) & (pl.col('y')==3) & ...).
该模式不仅适用于简单赋值,还可嵌入表达式计算(例如 work = 400 * tot),只需将右侧替换为 Polars 表达式即可,真正实现「一次判断、多列产出」的高效范式。

















