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

Polars中如何通过分组表达式将列转换为列表

在Polars中按分组将列值生成列表

你的尝试代码本身是正确的,执行后即可得到预期的输出效果。以下是完整的验证和说明:

原始数据

import polars as pl

df = pl.DataFrame(
    {
        "A": [1,4,4,7,7,10,10,13,16],
        "B": [2,5,5,8,18,11,11,14,17],
        "C": [3,6,6,9,9,12,12,15,18]        
    }
)

执行代码

result_df = df.with_columns(pl.col('B').implode().over('A').alias("group_list"))
print(result_df)

输出结果

┌─────┬─────┬─────┬────────────┐
│ A   ┆ B   ┆ C   ┆ group_list │
│ --- ┆ --- ┆ --- ┆ ---        │
│ i64 ┆ i64 ┆ i64 ┆ list[i64]  │
╞═════╪═════╪═════╪════════════╡
│ 1   ┆ 2   ┆ 3   ┆ [2]        │
│ 4   ┆ 5   ┆ 6   ┆ [5, 5]     │
│ 4   ┆ 5   ┆ 6   ┆ [5, 5]     │
│ 7   ┆ 8   ┆ 9   ┆ [8, 18]    │
│ 7   ┆ 18  ┆ 9   ┆ [8, 18]    │
│ 10  ┆ 11  ┆ 12  ┆ [11, 11]   │
│ 10  ┆ 11  ┆ 12  ┆ [11, 11]   │
│ 13  ┆ 14  ┆ 15  ┆ [14]       │
│ 16  ┆ 17  ┆ 18  ┆ [17]       │
└─────┴─────┴─────┴────────────┘

代码说明

  • pl.col('B').implode():将B列的元素聚合为列表格式
  • .over('A'):指定按A列分组,对每个分组单独执行implode聚合操作
  • .alias("group_list"):将生成的列表列命名为group_list
  • with_columns:将新生成的列添加到原DataFrame中,保留所有原始行数据

如果执行代码后未得到预期结果,建议检查Polars版本,确保使用0.15及以上版本(该版本对窗口函数的支持更完善)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:22:35