Pandas如何将ethnicity_name列展开为宽表并填充对应占比数值
Pandas 长表转指定宽表的最简实现
你需要的长表转宽表需求可以直接用Pandas内置的透视方法实现,无需手动做映射操作,以下是两种可行的简洁方案:
方案1:pivot方法(数据无重复分组时最优)
当你的原始数据中enrollment+teacher_salary+ethnicity_name组合唯一时,一行代码即可完成转换:
# 假设原始DataFrame名为df wide_df = df.pivot( index=["enrollment", "teacher_salary"], columns="ethnicity_name", values="ethnicity_percent" ).reset_index()
方案2:pivot_table方法(兼容性更强)
如果存在潜在的重复分组行,可以指定聚合规则避免报错,适配性更高:
wide_df = df.pivot_table( index=["enrollment", "teacher_salary"], columns="ethnicity_name", values="ethnicity_percent", aggfunc="first" # 同组取值一致时用first即可,也可根据需求替换为sum/mean等 ).reset_index()
如果需要严格按照要求的列顺序输出,转换完成后直接指定列顺序即可:
wide_df = wide_df[["enrollment", "teacher_salary", "African_American", "Caucasian", "Hispanic"]]
内容的提问来源于stack exchange,提问作者elby
相关产品推荐
相关产品推荐

