python - 如何合并 Pandas 数据透视表中的多索引层?

标签 python pandas merge pivot-table multi-index

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

    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/

相关文章:

python - 热将多个数据帧转换为特定格式?

git - 防止在 git 存储库中的 master 分支上直接提交并仅接受 merge ?

python - 单击链接时阻止 selenium 打开新窗口

python - 选择 numpy 列中的最大元素并获取其行

python - 使用接口(interface)/抽象基类是pythonic吗?

python - 如何在 EDA 过程中使用 Pandas DateTime 识别时间差异

python - 理解 Python super() 和 __init__() 方法

Python 字典到 R session

python - 使用相同的键在 Python 中合并两个字典

entity-framework - Entity Framework 合并梦Night