Polars 中使用 pl.when 条件表达式输出字符串字面量的正确方法

5次阅读

Polars 中使用 pl.when 条件表达式输出字符串字面量的正确方法

在 Polars 中,pl.when().then().otherwise() 无法直接使用纯字符串(如 ‘String a’)作为分支值,必须通过 pl.lit() 将其显式转为字面量表达式,否则会被误解析为列名并报 ColumnNotFoundError。

在 polars 中,`pl.when().then().otherwise()` 无法直接使用纯字符串(如 `’string a’`)作为分支值,必须通过 `pl.lit()` 将其显式转为字面量表达式,否则会被误解析为列名并报 `columnnotfounderror`。

Polars 的表达式系统严格区分列引用字面量值:当你在 .then(‘string a’) 中传入一个字符串时,Polars 默认将其视为对名为 “string a” 的列的引用(而非字符串内容本身),因此在列不存在时抛出 ColumnNotFoundError。这是初学者常见的误区,根源在于 Polars 表达式 API 的类型安全设计——所有标量值必须经由 pl.lit() 显式声明为字面量。

✅ 正确写法如下:

import polars as pl  # 示例数据 df = pl.DataFrame({"x": [1, 2, 3, 4]})  # 基于条件生成字符串列:x > 2 → "string a",否则 "string b" result = df.with_columns(     pl.when(pl.col("x") > 2)     .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 b   │ │ 2   ┆ string b   │ │ 3   ┆ string a   │ │ 4   ┆ string a   │ └─────┴────────────┘

⚠️ 注意事项:

  • pl.lit() 不仅适用于字符串,也适用于数字、布尔值、None、日期等任意 Python 标量(如 pl.lit(42), pl.lit(True), pl.lit(None));
  • 若需动态拼接字符串(如 “prefix_” + col_name),应使用pl.col(…).cast(pl.Utf8).str.concat(…)或pl.format(),而非在pl.lit()` 中拼接;
  • 在链式 .when().then().when().then().otherwise() 多条件结构中,每个 .then() 和最终 .otherwise() 都必须使用 pl.lit() 包裹字面量;
  • 错误示例(会报错):.then(“string a”)、.otherwise(100) —— 缺少 pl.lit 将导致类型推断失败或列查找异常。

? 小技巧:可将常用字面量封装变量提升可读性:

STR_A = pl.lit("string a") STR_B = pl.lit("string b")  df.with_columns(     pl.when(pl.col("x") > 2).then(STR_A).otherwise(STR_B).alias("new_column") )

总之,pl.lit() 是 Polars 表达式中“标量即值”的关键桥梁。养成对所有非列引用的静态值显式调用 pl.lit() 的习惯,是编写健壮、可维护 Polars 查询的基础。

text=ZqhQzanResources