Polars 中使用 pl.when 创建字符串条件列的正确方法

2次阅读

Polars 中使用 pl.when 创建字符串条件列的正确方法

在 Polars 中使用 pl.when().then().otherwise() 构建条件列时,若需输出字面量字符串(如 “String a”),必须用 pl.lit() 显式包装,否则 Polars 会误将其解析为列名,导致 columnNotFoundError。

在 polars 中使用 `pl.when().then().otherwise()` 构建条件列时,若需输出字面量字符串(如 `”string a”`),必须用 `pl.lit()` 显式包装,否则 polars 会误将其解析为列名,导致 `columnnotfounderror`。

Polars 的表达式系统默认将裸字符串(如 ‘string a’)解释为列引用(column name),而非字面量(literal value)。这是 Polars 与 pandas 等库的关键差异之一:其表达式 API 高度面向列操作,所有未显式声明为“字面量”的标量值都会被尝试解析为现有列名。因此,当您写下:

pl.when(df['x'] > 0).then('string a').otherwise('string b')

Polars 实际试图查找名为 “string a” 和 “string b” 的列——显然不存在,于是抛出 ColumnNotFoundError。

✅ 正确做法是使用 pl.lit() 将字符串转为字面量表达式:

import polars as pl  df = pl.DataFrame({"x": [1, -2, 0, 5]})  result = df.with_columns(     pl.when(pl.col("x") > 0)       .then(pl.lit("string a"))       .otherwise(pl.lit("string b"))       .alias("new_column") )  print(result)

输出:

shape: (4, 2) ┌─────┬────────────┐ │ x   ┆ new_column │ │ --- ┆ ---        │ │ i64 ┆ str        │ ╞═════╪════════════╡ │ 1   ┆ string a   │ │ -2  ┆ string b   │ │ 0   ┆ string b   │ │ 5   ┆ string a   │ └─────┴────────────┘

? 补充说明:

  • pl.lit() 不仅支持字符串,也适用于数字、布尔值、None、日期等任意 Python 标量;
  • 若 then/otherwise 分支需返回不同数据类型(如字符串 vs 整数),Polars 会自动推断为公共超类型(如 pl.String 和 pl.Int64 → pl.Object),建议保持类型一致以保障性能和类型安全;
  • 可链式嵌套多个 pl.when(类似 sql 的 CASE WHEN),例如:
    pl.when(cond1).then(pl.lit("A"))  .when(cond2).then(pl.lit("B"))  .otherwise(pl.lit("C"))

⚠️ 注意事项:

  • 切勿省略 pl.lit() —— 即使是空字符串 “” 或单字符 “X” 也必须包装;
  • pl.lit() 返回的是 polars.expr.Expr,可直接参与任何表达式组合;
  • select()、with_columns()、Filter() 等上下文中均适用,是 Polars 字面量操作的唯一标准方式。

掌握 pl.lit() 是写出健壮、可维护 Polars 表达式的基础技能之一:它明确区分了“数据”与“元数据”,让逻辑意图清晰无歧义。

text=ZqhQzanResources