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

如何在Polars DataFrame的列表列中按索引修改列表元素

在Polars DataFrame中按列表索引修改元素内容

要修改Polars DataFrame列表列中指定索引的元素,不能直接用你伪代码里的赋值方式,Polars提供了函数式操作方案,以下是两种可行方法:

方法1:使用list.set(推荐,Polars 0.18.0及以上版本支持)

该方法直接针对列表列的指定索引位置设置新值,语法简洁高效:

import polars as pl

df = pl.DataFrame({
    "values": [
        [10, 20, 30, 40], 
        [50, 60, 70, 80], 
        [90, 100, 110, 120],
    ],
})

df = df.with_columns(
    pl.col("values").list.set(3, 1).alias("values")
)
print(df)

输出结果:

shape: (3, 1)
┌───────────────────┐
│ values            │
│ ---               │
│ list[i64]         │
╞═══════════════════╡
│ [10, 20, 30, 1]   │
│ [50, 60, 70, 1]   │
│ [90, 100, 110, 1] │
└───────────────────┘

方法2:使用list.eval结合条件替换(兼容旧版本)

如果你的Polars版本较低不支持list.set,可以用list.eval配合pl.when条件判断生成新列表:

df = df.with_columns(
    pl.col("values").list.eval(
        pl.when(pl.int_range(pl.len()) == 3).then(1).otherwise(pl.element())
    ).alias("values")
)
print(df)

这里通过pl.int_range(pl.len())生成每个元素的索引,判断索引等于3时替换为1,否则保留原元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:50:11