使用Polars判断列值是否为指定字符串子串遇报错问题
解决方案
报错原因
你用pl.col("Col B")获取的是Polars的表达式对象(Expr),而apply是Polars Series的方法,不能直接在Expr上调用,因此触发AttributeError。
正确实现方式
方法一:使用Polars内置字符串函数(推荐,性能最优)
Polars提供了矢量化的字符串处理函数,直接用str.contains实现需求,注意要把固定字符串转为表达式,再检查它是否包含列中的每个值:
import polars as pl string_1 = "this example string" df = df.with_columns( pl.lit(string_1).str.contains(pl.col("Col B")).alias("new_col") )
方法二:用map_elements实现自定义逻辑
如果需要自定义更复杂的判断逻辑,可以用Expr的map_elements方法替代apply:
import polars as pl string_1 = "this example string" df = df.with_columns( pl.col("Col B").map_elements(lambda x: x in string_1).alias("new_col") )
注意:
map_elements是逐元素处理,性能远不如内置的矢量化函数,仅在复杂自定义场景下使用。
内容的提问来源于stack exchange,提问作者spg719
相关产品推荐
相关产品推荐

