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

如何在Polars中基于整数列生成对应范围的列表列?

问题

给定如下Polars DataFrame:

>>> df = pl.DataFrame({'l': [3,5,8]})
>>> df
shape: (3, 1)
┌─────┐
│ l   │
│ --- │
│ i64 │
╞═════╡
│ 3   │
│ 5   │
│ 8   │
└─────┘

如何生成包含整数列表的新列,得到如下结果?

>>> df
shape: (3, 2)
┌─────┬─────────────┐
│ l   ┆ column_0    │
│ --- ┆ ---         │
│ i64 ┆ list[i64]   │
╞═════╪═════════════╡
│ 3   ┆ [0, 1, 2]   │
│ 5   ┆ [0, 1, … 4] │
│ 8   ┆ [0, 1, … 7] │
└─────┴─────────────┘

我目前用map_rows实现,但数据量大时效率很低:

>>> temp = df.map_rows(lambda x: (list(range(x[0])),))
>>> df = df.hstack(temp)
高效解决方案

别用map_rows,Polars提供了原生向量化函数pl.int_range(旧版本可用pl.range),直接在列上操作就能生成目标列表,完全避免Python层面逐行循环,效率提升明显:

df = df.with_columns(
    pl.int_range(0, pl.col("l")).alias("column_0")
)

说明

  • pl.int_range(0, pl.col("l"))会对每行的l值,自动生成从0到l-1的整数列表,全程是Polars内部的向量化计算
  • 旧版Polars可以替换为pl.range(0, pl.col("l")),用法完全一致

运行后验证结果:

>>> df
shape: (3, 2)
┌─────┬─────────────┐
│ l   ┆ column_0    │
│ --- ┆ ---         │
│ i64 ┆ list[i64]   │
╞═════╪═════════════╡
│ 3   ┆ [0, 1, 2]   │
│ 5   ┆ [0, 1, … 4] │
│ 8   ┆ [0, 1, … 7] │
└─────┴─────────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:42:41