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

如何将Pandas DataFrame中type列取值转为列头 按id聚合result为对应值

你要实现的是Pandas长表转宽表的操作,直接用内置的pivot_table方法就能完成需求,示例代码如下:

import pandas as pd

# 假设你的原数据集存为变量 df
pivot_df = df.pivot_table(
    index=["id", "name"],
    columns="type",
    values="result",
    aggfunc="first"
).reset_index()

# 可选:将默认空值NaN替换为你需要的None
pivot_df = pivot_df.where(pd.notna(pivot_df), None)

如果你的数据中不存在同一个id+name+type对应多个result的情况,也可以用更轻量的pivot方法:

pivot_df = df.pivot(index=["id", "name"], columns="type", values="result").reset_index()
pivot_df = pivot_df.where(pd.notna(pivot_df), None)

执行上述代码后得到的pivot_df就是你需要的目标结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 17:42:02