如何在pandas数据透视表中合并多索引层?

2024-05-16 22:56:43 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我得到了球员在这样的比赛中表现的数据帧:

    Match    Faction    A         B
    BG1      Alliance   8         10
    BG1      Alliance   2         5
    BG1      Horde      5         25
    BG2 ...

我想汇总每场比赛的A和B组数据,换句话说,得到如下数据帧:

^{pr2}$

我知道我可以手动形成每个列,但我正在寻找更优雅的方法来解决这个问题。所以,我试了一下:

^{3}$

我得到了以下结论:

             A                B
    Faction  Alliance  Horde  Alliance  Horde
    Match  
    BG1      10        5      15        25  
    BG2 ...

现在,有没有办法将这些多个索引合并成“联盟A”、“部落A”、“联盟B”、“部落B”列?我唯一的想法就是申请

    .T.reset_index().T

…这将删除多个索引层,但是,它需要手动重命名之后的列。在


Tags: 数据方法match手动汇总球员alliance办法
1条回答
网友
1楼 · 发布于 2024-05-16 22:56:43

这很简单,因为你已经完成了大部分工作:

# 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')

相关问题 更多 >