Python Pandas:将行转换为列标题 [英] Python Pandas: Convert Rows as Column headers

查看:279
本文介绍了Python Pandas:将行转换为列标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

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 dont seem to work.

推荐答案

您正在寻找

You're looking for 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

,如果要重新排列各列:

and if you want to reorder the columns:

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

这篇关于Python Pandas:将行转换为列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆