假设我得到了球员在这样的比赛中表现的数据框:
Match Faction A B
BG1 Alliance 8 10
BG1 Alliance 2 5
BG1 Horde 5 25
BG2 ...
我想汇总每场比赛的球队统计数据 A 和 B,换句话说,获取这样的数据框:
Match Alliance A Alliance B Horde A Horde B
BG1 10 15 5 25
BG2 ...
我知道我可以手动形成每一列,但我一直在寻找更优雅的方法来解决问题。所以,我尝试了这个:
df.pivot_table(values=['A', 'B'], index='Match', columns='Faction', aggfunc=lambda x: x.sum())
这给了我以下内容:
A B
Faction Alliance Horde Alliance Horde
Match
BG1 10 5 15 25
BG2 ...
现在,有什么方法可以合并这些多索引,将它们变成“联盟 A”、“部落 A”、“联盟 B”、“部落 B”列?我唯一的想法是申请
.T.reset_index().T
...这会删除多索引层,但是,它需要手动重命名之后的列。
最佳答案
这很容易,因为您已经完成了大部分工作:
# create a list of the new column names in the right order
new_cols=[('{1} {0}'.format(*tup)) for tup in pivoted.columns]
# assign it to the dataframe (assuming you named it pivoted
pivoted.columns= new_cols
# resort the index, so you get the columns in the order you specified
pivoted.sort_index(axis='columns')
关于python - 如何合并 Pandas 数据透视表中的多索引层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57439746/