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

如何将多列多行数据合并为Polars结构体(字典)

使用Polars将DataFrame转换为嵌套结构并输出JSON Lines格式

方法一:聚合+字典转换(通用场景)

通过分组聚合将每组的label和indicator转换为字典结构体,再输出JSON Lines:

import polars as pl

df = pl.DataFrame({
    "group_id": ["a", "a", "a", "b", "b", "b"],
    "label": ["dog", "cat", "mouse", "dog", "cat", "mouse"],
    "indicator": [1, 1, 0, 0, 0, 1]
})

# 转换为嵌套结构
result = (
    df
    .group_by("group_id")
    .agg(
        # 将每组的label和indicator打包为结构体数组,再转换为字典
        pl.struct("label", "indicator")
        .map_elements(lambda items: {item["label"]: item["indicator"] for item in items}, return_dtype=pl.Object)
        .alias("label")
    )
)

# 输出JSON Lines格式数据
print(result.write_ndjson())

方法二:透视+结构体打包(高效矢量化操作)

由于所有分组的标签集合一致,推荐使用pivot结合row_to_structs的矢量化方案,性能更优:

result = (
    df
    .pivot(
        index="group_id",
        columns="label",
        values="indicator"
    )
    # 将透视后的列打包为名为label的结构体
    .row_to_structs(output_col="label", exclude=["group_id"])
)

print(result.write_ndjson())

结果验证

  • 查看转换后的DataFrame结构:

    print(result)
    

    输出与目标结构一致:

    ┌──────────┬───────────┐
    │ group_id ┆ label     │
    │ ---      ┆ ---       │
    │ str      ┆ struct[3] │
    ╞══════════╪═══════════╡
    │ a        ┆ {1,1,0}   │
    │ b        ┆ {0,0,1}   │
    └──────────┴───────────┘
    
  • 查看单个字典内容:

    print(result["label"][0])
    

    输出:{'dog': 1, 'cat': 1, 'mouse': 0}

  • 最终JSON Lines输出:

    {"group_id":"a","label":{"dog":1,"cat":1,"mouse":0}}
    {"group_id":"b","label":{"dog":0,"cat":0,"mouse":1}}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:51:31