Python Pandas:将行转换为列标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17298313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:48:57  来源:igfitidea点击:

Python Pandas: Convert Rows as Column headers

pythonpandas

提问by richie

I have the following dataframe:

我有以下数据框:

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

I want it this way.

我想要这样。

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

Stack/Unstack dont seem to work.

Stack/Unstack 似乎不起作用。

采纳答案by Andy Hayden

You're looking for pivot_table:

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

回答by Manu Sharma

Stack/ Unstack won't work until you have the desired column in your row/ column indexes. e.g. In simple words, Stack/ Unstack will bring the lowest level of column index to the lowest level of row index and vice versa.

在行/列索引中有所需的列之前,堆栈/取消堆栈将不起作用。例如,简单来说,Stack/Unstack 会将最低级别的列索引带到最低级别的行索引,反之亦然。

So in your case, you can achieve the same results with stack/unstack by

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

enter image description here

在此处输入图片说明