You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars教程:如何使用pl.when输出字符串类型值

解决Polars pl.when中字符串字面量被识别为列名的问题

在Polars里,pl.when()的.then()和.otherwise()方法默认会把传入的字符串当成列名解析,而非字面量值,这就是你触发ColumnNotFoundError: string a错误的原因。要让Polars识别这是固定字符串值,得用pl.lit()函数把字符串包裹起来。

正确代码示例

pl.when(condition)
  .then(pl.lit('string a'))
  .otherwise(pl.lit('string b'))
  .alias('new column')

说明

pl.lit()是Polars用来创建字面量表达式的工具,它明确告知Polars:传入的内容是一个固定值,不是要引用的列名。这样执行后,新列就能根据条件正确输出"string a"或"string b"。

内容的提问来源于stack exchange,提问作者noobanalyst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:02:01