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

如何用Polars将多行聚合为单行并将列值转为逗号分隔字符串?

解决方案

直接聚合为逗号分隔字符串(无需中间列表步骤)

你可以直接在group_by.agg中使用Polars原生的str.join方法,一步完成分组与字符串拼接:

import polars as pl

df = pl.from_repr("""
┌───────────────┬──────────────┬───────────────┐
│ schema_name   ┆ table_name   ┆ column_name   │
│ ---           ┆ ---          ┆ ---           │
│ str           ┆ str          ┆ str           │
╞═══════════════╪══════════════╪═══════════════╡
│ test_schema   ┆ test_table   ┆ test_column   │
│ test_schema   ┆ test_table   ┆ test_column   │
│ test_schema_2 ┆ test_table_2 ┆ test_column_2 │
└───────────────┴──────────────┴───────────────┘
""")

result = df.group_by(['schema_name', 'table_name']).agg(
    pl.col('column_name').str.join(', ').alias('column_name')
)

print(result)

执行后输出目标结果:

shape: (2, 3)
┌───────────────┬──────────────┬──────────────────────────┐
│ schema_name   ┆ table_name   ┆ column_name              │
│ ---           ┆ ---          ┆ ---                      │
│ str           ┆ str          ┆ str                      │
╞═══════════════╪══════════════╪══════════════════════════╡
│ test_schema_2 ┆ test_table_2 ┆ test_column_2            │
│ test_schema   ┆ test_table   ┆ test_column, test_column │
└───────────────┴──────────────┴──────────────────────────┘

将已有的列表字段转为逗号分隔字符串

如果已经生成了含列表的中间结果,同样用str.join方法直接转换即可:

# 先得到带列表的中间DataFrame
list_df = df.group_by(['schema_name', 'table_name']).agg(
    pl.col('column_name').alias('column_list')
)

# 把列表列转为逗号分隔字符串
result = list_df.with_columns(
    pl.col('column_list').str.join(', ').alias('column_name')
).drop('column_list')

print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:35:19