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

如何在Polars中实现列表的累积去重扩展?

实现Polars累积去重列表列

你可以通过cumulative_eval结合列表拼接、扁平化和去重操作来实现需求,具体代码如下:

import polars as pl

df = pl.DataFrame({
    "col": [["a"],  ["a", "b"],  ["c"]]
})

# 添加累积去重列
result = df.with_columns(
    col_cum=pl.col("col").cumulative_eval(
        pl.concat_list(pl.col("col")).flatten().unique()
    )
)

print(result)

代码说明

  • cumulative_eval会以从第一行到当前行的col列数据作为计算窗口,逐行生成结果
  • pl.concat_list(pl.col("col"))将当前窗口内的所有子列表拼接成一个嵌套大列表
  • .flatten()把嵌套列表展开为一维元素列表,方便后续去重
  • .unique()对展开后的列表去重,得到最终的累积去重列表

运行后输出结果与你预期完全一致:

┌────────────┬─────────────────┐
│ col        ┆ col_cum         │
│ ---        ┆ ---             │
│ list[str]  ┆ list[str]       │
╞════════════╪═════════════════╡
│ ["a"]      ┆ ["a"]           │
│ ["a", "b"] ┆ ["a", "b"]      │
│ ["c"]      ┆ ["a", "b", "c"] │
└────────────┴─────────────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:24:18