【问题标题】:Python Pandas: Convert Rows as Column headers [duplicate]Python Pandas:将行转换为列标题[重复]
【发布时间】:2013-06-22 07:23:24
【问题描述】:

我有以下数据框:

Year    Country          medal    no of medals
1896    Afghanistan      Gold        5
1896    Afghanistan      Silver      4
1896    Afghanistan      Bronze      3
1896    Algeria          Gold        1
1896    Algeria          Silver      2
1896    Algeria          Bronze      3

我想要这样。

Year    Country      Gold   Silver   Bronze
1896    Afghanistan    5      4         3
1896    Algeria        1      2         3

Stack/Unstack 似乎不起作用。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您正在寻找pivot_table:

    In [11]: medals = df.pivot_table('no of medals', ['Year', 'Country'], 'medal')
    
    In [12]: medals
    Out[12]:
    medal             Bronze  Gold  Silver
    Year Country
    1896 Afghanistan       3     5       4
         Algeria           3     1       2
    

    如果您想对列重新排序:

    In [12]: medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)
    Out[12]:
    medal             Gold  Silver  Bronze
    Year Country
    1896 Afghanistan     5       4       3
         Algeria         1       2       3
    

    【讨论】:

    • 这会创建一个多级索引,这不是 100% 想要的。通过medals.reset_index( drop=False, inplace=True ) 摆脱它,然后通过medals.reindex_axis(['Year', 'Country', 'Gold', 'Silver', 'Bronze'], axis=1) 关注
    • Python v3.6+ '.reindex_axis' is deprecated and will be removed in a future version. Use '.reindex' instead.
    【解决方案2】:

    在您的行/列索引中有所需的列之前,Stack/Unstack 将无法工作。例如简单来说,Stack/Unstack 会将最低级别的列索引带到最低级别的行索引,反之亦然。

    因此,在您的情况下,您可以通过 stack/unstack by 实现相同的结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多