Python Pandas: 将行转换为列标题

114

我有以下数据框:

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

堆叠/展开似乎无法正常工作。

2个回答

145
你正在寻找 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

19
这将创建一个多层索引,这不完全是想要的。通过medals.reset_index(drop=False, inplace=True)去除它,然后跟随medals.reindex_axis(['Year', 'Country', 'Gold', 'Silver', 'Bronze'], axis=1) - madoki
3
Python v3.6+ 中的 '.reindex_axis' 已经被弃用,并将在未来版本中被移除。请使用 .reindex 替代。 - Bn.F76

15

如果你的行/列索引中没有所需的列,那么Stack / Unstack将无法工作。简单来说,Stack / Unstack将把列索引的最低级别带到行索引的最低级别,反之亦然。

因此,在你的情况下,你可以通过以下方式使用stack/unstack来实现相同的结果:

df.set_index(['Year','Country','medal'], drop=True).unstack('medal')

输入图片描述


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