pandas如何将含Method列的长表动态转换为按ID、type分组的宽表
你可以直接使用 pandas 内置的pivot方法实现动态转换,无需手动指定所有 Method 列:
核心实现代码
import pandas as pd # 你原有的加载逻辑 results = [{'ID': 0,'type': 'gas', 'Method': 'M1', 'Score': 0.50}, {'ID': 0,'type': 'gas', 'Method': 'M2', 'Score': 0.80}, {'ID': 1,'type': 'coal', 'Method': 'M1', 'Score': 0.81}, {'ID': 1,'type': 'coal', 'Method': 'M2', 'Score': 0.49}, {'ID': 2,'type': 'wind', 'Method': 'M1', 'Score': 0.34}, {'ID': 2,'type': 'wind', 'Method': 'M2', 'Score': 0.94}] df = pd.DataFrame(results, columns=["ID","type", "Method", "Score"]) # 长表转宽表核心逻辑 df_wide = df.pivot( index=['ID', 'type'], columns='Method', values='Score' ).reset_index() # 可选:清除列名的层级标识,保持列名整洁 df_wide.columns.name = None
说明
pivot方法会自动提取Method列的所有唯一值作为新列,适配M1到Mn任意数量的动态Method场景。- 如果存在同一个
ID+type+Method组合对应多个Score的场景,可以替换为pivot_table指定聚合规则,示例如下:
df_wide = df.pivot_table( index=['ID', 'type'], columns='Method', values='Score', aggfunc='mean' # 可根据需求替换为sum、max、min等聚合函数 ).reset_index() df_wide.columns.name = None
运行后输出的df_wide就是你需要的宽表结构。
内容的提问来源于stack exchange,提问作者Shadowhonor
相关产品推荐
相关产品推荐

