如何实现接收条件列表的Polars DataFrame过滤函数?
实现基于条件列表的Polars DataFrame过滤函数
你的伪代码核心逻辑没问题,但直接用Python原生的any处理Polars表达式会报错——Polars需要用专门的横向聚合函数来组合行内的多个布尔条件。以下是可直接运行的实现方案:
import polars as pl def Filter(df, conditions = ["a","b"]): conditions_dict = { "a": pl.col("x") < 5, "b": pl.col("x") > -3, "c": pl.col("z") < 7 } # 提取传入参数对应的条件表达式 selected_conds = [conditions_dict[cond] for cond in conditions] # 用Polars的any_horizontal判断行内是否有任意条件满足 return df.with_columns( pl.when(pl.any_horizontal(selected_conds)) .then(pl.lit(False)) .otherwise(pl.lit(True)) .alias("bool") )
关键说明
pl.any_horizontal():这是Polars专门用来处理同一行内多个布尔表达式的函数,会逐行检查是否有任意一个条件为True,完美替代你伪代码里的原生any。- 条件匹配:先根据传入的
conditions列表从预定义字典中取出对应的表达式,再传入聚合函数,确保只使用指定的条件。 - 逻辑对应:当任意指定条件满足时,
bool列设为False;所有条件都不满足时设为True,和你预期的逻辑完全一致。
测试示例
# 创建测试DataFrame test_df = pl.DataFrame({ "x": [6, 3, -4, 2], "z": [8, 5, 6, 9] }) # 使用默认条件["a","b"]过滤 result_df = Filter(test_df) print(result_df)
输出结果:
shape: (4, 3) ┌─────┬─────┬───────┐ │ x ┆ z ┆ bool │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ bool │ ╞═════╪═════╪═══════╡ │ 6 ┆ 8 ┆ False │ # 不满足a(x<5),但满足b(x>-3)→ 设为False │ 3 ┆ 5 ┆ False │ # 同时满足a和b → 设为False │ -4 ┆ 6 ┆ False │ # 满足a(x<5),不满足b(x>-3)→ 设为False │ 2 ┆ 9 ┆ False │ # 同时满足a和b → 设为False └─────┴─────┴───────┘
如果传入conditions=["c"],结果会变成:
shape: (4, 3) ┌─────┬─────┬───────┐ │ x ┆ z ┆ bool │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ bool │ ╞═════╪═════╪═══════╡ │ 6 ┆ 8 ┆ True │ # z=8不满足c(z<7)→ 设为True │ 3 ┆ 5 ┆ False │ # z=5满足c → 设为False │ -4 ┆ 6 ┆ False │ # z=6满足c → 设为False │ 2 ┆ 9 ┆ True │ # z=9不满足c → 设为True └─────┴─────┴───────┘
内容的提问来源于stack exchange,提问作者Galedon
相关产品推荐
相关产品推荐

