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

Polars中如何对包含列表元素的两个Series执行加法操作

解决Polars中List[i64]类型Series的逐元素加减问题

Polars 默认不支持直接对 list[i64] 类型的 Series 使用 +/- 运算符执行逐元素加减,需要通过列表专用的操作函数实现需求。以下是两种高效的实现方式:

方法1:利用Series.zip结合list.eval

通过Series.zip将两个Series的对应列表配对,再用list.eval对每对列表执行逐元素相加:

import polars as pl

a = pl.Series("a", [[1,2],[2,3]])
b = pl.Series("b", [[4,5],[6,7]])

# 逐元素相加
c = pl.Series.zip(a, b).list.eval(pl.element()[0] + pl.element()[1])
print(c.to_list())
# 输出:[[5, 7], [8, 10]]

方法2:在DataFrame中使用struct.map_elements

将两个Series放入DataFrame,通过struct打包后使用map_elements遍历处理每一行的列表:

import polars as pl

df = pl.DataFrame({
    "a": [[1,2],[2,3]],
    "b": [[4,5],[6,7]]
})

df = df.with_columns(
    pl.struct(["a", "b"]).map_elements(
        lambda x: [x["a"][i] + x["b"][i] for i in range(len(x["a"]))],
        return_dtype=pl.List(pl.Int64)
    ).alias("c")
)

print(df["c"].to_list())
# 输出:[[5, 7], [8, 10]]

注意事项

  • 确保两个Series中对应位置的列表长度一致,否则会引发索引越界错误。
  • 方法1基于Polars内置的列表操作函数,性能优于方法2的Python lambda遍历,数据量较大时更推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:52:58