如何用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
相关产品推荐
相关产品推荐

