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

Polars中如何高效替换List列列表内的元素?

在Polars中高效替换List列内的元素

当然可以,以下是两种高效的实现方式:

方法一:使用list.eval结合条件表达式

这是Polars原生的向量化操作,性能最优,直接在列表元素层面做条件判断替换:

import polars as pl

s = pl.Series('s', [[1, 2, 3], [3, 4, 5]])
res = s.to_frame().with_columns(
    pl.col("s").list.eval(
        pl.element().when(pl.element() == 3).then(10).otherwise(pl.element())
    ).alias("s")
).to_series()

print(res)
# 输出:
# shape: (2,)
# Series: 's' [list[i64]]
# [
#  [1, 2, 10]
#  [10, 4, 5]
# ]

其中list.eval会遍历每个子列表,pl.element()专门指代子列表中的单个元素,通过when/then/otherwise完成值的替换逻辑。

方法二:使用list.eval结合replace方法

如果只是单一值的替换,用replace方法语法更简洁,性能和第一种方法接近:

res = s.to_frame().with_columns(
    pl.col("s").list.eval(pl.element().replace(3, 10)).alias("s")
).to_series()

关于之前尝试的问题说明

  • 直接用pl.when()无法处理List[bool],是因为pl.when()默认是列级别的判断,无法直接作用于列表内部的元素;
  • 使用list.eval时需要通过pl.element()来访问子列表里的元素,这是之前可能遗漏的关键语法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 17:17:34