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

