如何在pandas透视表中合并多个索引层级?

3
假设我有一个包含选手在比赛中表现的数据框,如下所示:
    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

...这会删除多重索引层,但需要手动重命名列。

1个回答

4

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

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

谢谢,这正是我所需要的。 - test_subject
不用客气。顺便说一下,我刚刚修改了代码,因为连接有时候会出现问题。我想使用格式更加安全。例如,如果您的列索引具有非字符串级别,则格式应该可以自动处理此类问题。 - jottbe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接