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

Polars:分组时f64列转字符串并聚合为列表的问题

问题解决:Polars分组聚合生成列表格式列

问题分析

你之前的代码错误在于使用map_elements(lambda x: str(x))时,x代表的是分组后的整个Series对象,而非单个元素,因此str(x)会返回Series的字符串描述(包含shape、类型等元信息),而非目标列表格式。正确的思路是先对每个元素做类型转换,再用Polars内置的list()聚合函数收集为列表。

解决方案

1. 聚合为list[f64]格式

直接使用list()聚合函数,保留原始浮点类型:

import polars as pl

df = pl.DataFrame({
    'order': [38681.0, 38692.0, 38680.0, 38693.0],
    'shipto': ["471433", "239269", "471433","239269"],
    'value': [10,20,30,None]
})

result_f64 = (
    df
    .group_by('shipto')
    .agg(
        pl.col('order').list().alias('order_list'),
        pl.sum('value').alias('total_value')
    )
)
print(result_f64)

输出结果:

shape: (2, 3)
┌────────┬───────────────────┬─────────────┐
│ shipto ┆ order_list        ┆ total_value │
│ ---    ┆ ---               ┆ ---         │
│ str    ┆ list[f64]         ┆ i64         │
╞════════╪═══════════════════╪═════════════╡
│ 471433 ┆ [38681.0, 38680.0] ┆ 40          │
│ 239269 ┆ [38692.0, 38693.0] ┆ 20          │
└────────┴───────────────────┴─────────────┘

2. 聚合为list[str]格式

先通过cast(str)将浮点值转为字符串,再用list()聚合:

result_str = (
    df
    .group_by('shipto')
    .agg(
        pl.col('order').cast(str).list().alias('order_list'),
        pl.sum('value').alias('total_value')
    )
)
print(result_str)

输出结果:

shape: (2, 3)
┌────────┬─────────────────────┬─────────────┐
│ shipto ┆ order_list          ┆ total_value │
│ ---    ┆ ---                 ┆ ---         │
│ str    ┆ list[str]           ┆ i64         │
╞════════╪═════════════════════╪═════════════╡
│ 471433 ┆ ["38681.0", "38680.0"] ┆ 40          │
│ 239269 ┆ ["38692.0", "38693.0"] ┆ 20          │
└────────┴─────────────────────┴─────────────┘

3. 优化:去掉字符串中的.0

如果不需要保留小数点后缀,可以先转整数再转字符串:

result_str_clean = (
    df
    .group_by('shipto')
    .agg(
        pl.col('order').cast(int).cast(str).list().alias('order_list'),
        pl.sum('value').alias('total_value')
    )
)
print(result_str_clean)

输出结果:

shape: (2, 3)
┌────────┬───────────────────┬─────────────┐
│ shipto ┆ order_list        ┆ total_value │
│ ---    ┆ ---               ┆ ---         │
│ str    ┆ list[str]         ┆ i64         │
╞════════╪═══════════════════╪═════════════╡
│ 471433 ┆ ["38681", "38680"] ┆ 40          │
│ 239269 ┆ ["38692", "38693"] ┆ 20          │
└────────┴───────────────────┴─────────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:45:30