如何用Polars在多列搜索字符串并生成标记列?求with_columns简洁写法
在Polars中用更简洁的方式实现多列字符串匹配标记
问题说明
现有Polars代码可实现多列搜索指定字符串,任意列匹配则生成值为1的标记列,否则为0。但希望在
with_columns()方法内用更简洁的写法完成相同功能,现有代码及运行结果如下:
现有代码
import polars as pl df = pl.DataFrame({ "col1": ["hello", "world", "polars"], "col2": ["data", "science", "hello"], "col3": ["test", "string", "match"], "col4": ["hello", "example", "test"] }) search_string = "hello" condition = pl.lit(False) for col in df.columns: condition |= pl.col(col).str.contains(search_string) df = df.with_columns( condition.alias("string_found") + 0 ) print(df)
现有代码运行结果
shape: (3, 5) ┌────────┬─────────┬────────┬─────────┬──────────────┐ │ col1 ┆ col2 ┆ col3 ┆ col4 ┆ string_found │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str ┆ i32 │ ╞════════╪═════════╪════════╪═════════╪══════════════╡ │ hello ┆ data ┆ test ┆ hello ┆ 1 │ │ world ┆ science ┆ string ┆ example ┆ 0 │ │ polars ┆ hello ┆ match ┆ test ┆ 1 │ └────────┴─────────┴────────┴─────────┴──────────────┘
简洁实现方案
方案1:使用pl.any_horizontal()(推荐)
利用Polars的横向聚合函数any_horizontal(),一行代码完成逻辑:
import polars as pl df = pl.DataFrame({ "col1": ["hello", "world", "polars"], "col2": ["data", "science", "hello"], "col3": ["test", "string", "match"], "col4": ["hello", "example", "test"] }) search_string = "hello" df = df.with_columns( pl.any_horizontal(pl.all().str.contains(search_string)).cast(pl.Int32).alias("string_found") ) print(df)
pl.all()选中所有列,对每列执行字符串匹配any_horizontal()横向检查任意列是否匹配成功(返回布尔值).cast(pl.Int32)把布尔值转成整数(True→1,False→0)
方案2:指定部分列匹配
如果只需要检查部分列,把pl.all()换成目标列名列表即可:
df = df.with_columns( pl.any_horizontal(pl.col(["col1", "col2", "col4"]).str.contains(search_string)).cast(pl.Int32).alias("string_found") )
方案3:用pl.max_horizontal()间接实现
布尔值转成整数后,最大值为1代表有匹配,0则无匹配,用max_horizontal()取横向最大值:
df = df.with_columns( pl.max_horizontal(pl.all().str.contains(search_string).cast(pl.Int32)).alias("string_found") )
以上三种方案的运行结果均与原有代码完全一致。
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

