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

如何在Polars中动态生成when-then表达式并合并多条件结果?

Polars动态生成多条件匹配并合并结果的高效实现

问题背景

当前使用的Polars表达式如下:

pl.when(pl.col(a).contains("some value")).then(pl.concat_list("ArayColumn"),[A])
  .when(pl.col(a).contains("some value")).then(pl.concat_list("ArayColumn"),[B])
  .when(pl.col(a).contains("some value")).then(pl.concat_list("ArayColumn"),[C])
  .otherwise("Z is Big").alias("Bigger Value")

需要动态生成这类多条件匹配表达式,伪代码逻辑如下:

exprs = []
for i,value in conditions: 
  exprs.append(pl.when(i).then(value))

exprs.otherwise(defaultValue).alias("Bigger Value")

最终要实现:对每行数据依次匹配所有when-then条件,合并所有符合条件的结果(如[A,B,C]),无匹配时返回默认值。

已尝试方案的问题:

  • 循环逐个应用表达式:大数据量下性能崩溃;
  • 链式调用when-then:Polars默认otherwise返回None,性能较慢。

高效实现方案

通过「生成多条件匹配表达式→合并过滤空值→处理默认情况」的流程实现,完全满足「先生成表达式再应用」的要求,且性能高效。

1. 定义条件与默认值

先准备好条件列表(每个元素是(匹配条件, 对应返回值)):

conditions = [
    (pl.col("a").contains("value1"), "A"),
    (pl.col("a").contains("value2"), "B"),
    (pl.col("a").contains("value3"), "C"),
]
default_value = "Z is Big"

2. 动态生成最终表达式

遍历条件生成单个匹配逻辑,再合并为列表并过滤空值:

# 生成单个条件的表达式:满足条件返回对应值,否则返回None
conditional_exprs = [pl.when(cond).then(val) for cond, val in conditions]

# 合并所有结果为列表,过滤空值,无匹配时返回默认值
final_expr = (
    pl.concat_list(conditional_exprs)
    .list.eval(pl.element().drop_nulls())  # 移除列表中的空值
    .list.eval(
        pl.when(pl.element().length() == 0)
        .then(default_value)
        .otherwise(pl.element())
    )
    .alias("Bigger Value")
)

3. 应用到DataFrame

直接调用with_columns完成处理:

df = df.with_columns(final_expr)

方案优势

  • 全动态生成表达式,无需手动编写链式when-then;
  • 仅单次DataFrame操作,避免循环处理的性能损耗;
  • 显式处理空值逻辑,规避Polars默认otherwise的性能问题;
  • 自动合并所有符合条件的结果,无匹配时返回预设默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:37:44