
在 Polars 中使用 pl.when().then().otherwise() 创建条件字符串列时,必须用 pl.lit() 包裹字符串字面量,否则 Polars 会误将其解析为列名,导致 ColumnNotFoundError。
在 polars 中使用 `pl.when().then().otherwise()` 创建条件字符串列时,必须用 `pl.lit()` 包裹字符串字面量,否则 polars 会误将其解析为列名,导致 `columnnotfounderror`。
Polars 的表达式系统严格区分列引用与字面量值:当你直接写 'string a',Polars 默认将其视为列名(即尝试查找名为 "string a" 的列),而非一个静态字符串值。这与 Pandas 的 np.where 或 Python 原生条件表达式行为不同,是 Polars 类型安全与惰性计算设计的体现。
要正确输出字符串字面量,需使用 pl.lit() 显式声明该值为常量(literal)。pl.lit() 会将 Python 基本类型(如 str, int, bool, None)包装为 Polars 表达式中的标量字面量,在所有行中保持一致。
✅ 正确用法示例:
import polars as pl
# 示例数据
df = pl.DataFrame({
"score": [85, 42, 96, 55]
})
# 创建条件字符串列:高分标记为 "excellent",其余为 "needs_review"
result_df = df.with_columns(
pl.when(pl.col("score") >= 90)
.then(pl.lit("excellent"))
.otherwise(pl.lit("needs_review"))
.alias("performance")
)
print(result_df)输出:
shape: (4, 2) ┌───────┬─────────────┐ │ score ┆ performance │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═══════╪═════════════╡ │ 85 ┆ needs_review│ │ 42 ┆ needs_review│ │ 96 ┆ excellent │ │ 55 ┆ needs_review│ └───────┴─────────────┘
⚠️ 注意事项:
- pl.lit() 不仅适用于字符串,也适用于数字、布尔值、None(对应 Polars 的 Null)等,例如 pl.lit(42)、pl.lit(True)、pl.lit(None);
- 若 .then() 或 .otherwise() 中混用列表达式与字面量(如 pl.lit("a") 和 pl.col("col_b")),Polars 会自动广播字面量以匹配行数,无需额外处理;
- 避免遗漏 pl.lit() —— 即使只在 .then() 中漏写,也会触发错误;.otherwise() 同样需要;
- 在链式调用中,可结合多个 pl.when 实现多分支逻辑(类似 SQL 的 CASE WHEN),每个分支的 then() 均需 pl.lit() 保障字面量语义。
? 小技巧:若需动态拼接字符串(如 "ID_" + pl.col("id").cast(pl.Utf8)),应使用 pl.format() 或 + 运算符,而非 pl.lit() —— pl.lit() 仅用于固定不变的常量值。
总结:pl.when(...).then(...).otherwise(...) 是 Polars 中实现向量化条件赋值的核心模式,而 pl.lit() 是确保字面量被正确定义的必要桥梁。掌握这一组合,即可稳健构建清晰、高效、类型明确的字符串条件列。










