[英]How to merge multi-index layers in pandas pivot-table?
假设我得到了像这样的比赛中球员表现的数据框:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.