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

如何获取Polars列表中元素的当前索引?

在Polars中获取列表元素的索引并进行计算

Polars目前没有直接提供pl.element().idx()这类获取列表元素索引的方法,但可以通过生成对应长度的索引序列来实现你的需求:

import polars as pl

data = {"a": [[1,2,3],[4,5,6]]}
schema = {"a": pl.List(pl.Int8)}

df = pl.DataFrame(data, schema=schema)

df = df.with_columns(
    pl.col("a").list.eval(pl.element() * pl.int_range(pl.len()))
)

print(df)

输出结果:

shape: (2, 1)
┌───────────┐
│ a         │
│ ---       │
│ list[u8]  │
├───────────┤
│ [0, 2, 6] │
│ [0, 5, 12]│
└───────────┘

原理说明:在list.eval闭包内,pl.len()会返回当前列表的长度,pl.int_range(pl.len())生成从0开始、长度与列表一致的整数序列,将这个序列和pl.element()(当前遍历到的列表元素)相乘,就能得到元素值乘以其索引的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:48:10