使用Polars的when()方法时遭遇ColumnNotFoundError报错求助
解决Polars中when+str.contains的ColumnNotFoundError报错
错误原因分析
ColumnNotFoundError 通常有两种触发场景:
- DataFrame中不存在你指定的
Foo列(注意Polars对列名大小写敏感) str.contains默认启用正则匹配,你要匹配的字符串里包含.(正则通配符),导致匹配逻辑异常(这种情况偶尔会被误报为列不存在)
解决方案
1. 先确认列名正确性
先打印所有列名排查:
print(df.columns)
如果Foo不在输出列表里,修正pl.col()中的列名(比如实际是foo或FOO)。
2. 修正字符串匹配逻辑
如果列名确认无误,是正则匹配的问题,两种解决方式:
方式一:转义正则特殊字符
把字符串中的.转义为\.,用原始字符串(前缀r)避免转义冲突:
df = df.with_columns( pl.when(pl.col("Foo").str.contains(r"Foo message\. Bar Message\.")) .then("Foo message") .alias("Foo_Column") )
方式二:启用字面量匹配
关闭正则模式,直接按纯文本匹配:
df = df.with_columns( pl.when(pl.col("Foo").str.contains("Foo message. Bar Message.", literal=True)) .then("Foo message") .alias("Foo_Column") )
内容的提问来源于stack exchange,提问作者Guilherme Noronha
相关产品推荐
相关产品推荐

