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

如何在Polars中实现列表内容按指定次数重复合并

如何在Polars中按指定次数重复列表元素

要实现Python中[1,2,3,4] * 3这种将列表元素展开重复的效果(即把列表内容在单个列表内重复指定次数),针对你提供的DataFrame,可以通过**repeat_by + list.concat**的组合实现,这是Polars原生的高效方法。

示例数据

import polars as pl

df = pl.DataFrame({
    "col1": [[1, 2, 3], [4, 5], [6, 7, 8, 9], [10]],
    "col2": [1, 2, 3, 2]
})

解决方案代码

result_df = df.select(
    pl.col("col1")
    .repeat_by(pl.col("col2"))  # 将col1的列表按col2指定次数重复,得到嵌套列表
    .list.concat()              # 将嵌套列表拼接为单层列表
    .alias("result")
)

执行结果

shape: (4, 1)
┌───────────────────────────────────┐
│ result                            │
│ ---                               │
│ list[i64]                         │
╞═══════════════════════════════════╡
│ [1, 2, 3]                         │
│ [4, 5, 4, 5]                      │
│ [6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9] │
│ [10, 10]                          │
└───────────────────────────────────┘

原理说明

  • repeat_by(pl.col("col2")):对每行的col1列表,按照col2的数值重复对应次数,生成嵌套列表(如[4,5]重复2次得到[[4,5], [4,5]])。
  • list.concat():将嵌套的子列表全部拼接成一个单层列表,正好对应Python中列表乘法的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 07:54:54