Python 如何在 Pandas 中透视数据框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28337117/
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
How to pivot a dataframe in Pandas?
提问by bjurstrs
I have a table in csv format that looks like this. I would like to transpose the table so that the values in the indicator name column are the new columns,
我有一个 csv 格式的表格,看起来像这样。我想转置表格,以便指标名称列中的值是新列,
Indicator Country Year Value
1 Angola 2005 6
2 Angola 2005 13
3 Angola 2005 10
4 Angola 2005 11
5 Angola 2005 5
1 Angola 2006 3
2 Angola 2006 2
3 Angola 2006 7
4 Angola 2006 3
5 Angola 2006 6
I would like the end result to like like this:
我希望最终结果像这样:
Country Year 1 2 3 4 5
Angola 2005 6 13 10 11 5
Angola 2006 3 2 7 3 6
I have tried using a pandas data frame with not much success.
我曾尝试使用 Pandas 数据框,但收效甚微。
print(df.pivot(columns = 'Country', 'Year', 'Indicator', values = 'Value'))
Any thoughts on how to accomplish this?
关于如何实现这一点的任何想法?
Thanks
谢谢
采纳答案by JAB
You can use pivot_table
:
您可以使用pivot_table
:
pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index()
this outputs:
这输出:
Indicator Country Year 1 2 3 4 5
0 Angola 2005 6 13 10 11 5
1 Angola 2006 3 2 7 3 6
回答by Jason Sprong
This is a guess: it's not a ".csv" file, but a Pandas DataFrame imported from a '.csv'.
这是一个猜测:它不是“.csv”文件,而是从“.csv”导入的 Pandas DataFrame。
To pivot this table you want three arguments in your Pandas "pivot". e.g., if
df
is your dataframe:
要旋转此表,您需要在 Pandas“枢轴”中使用三个参数。例如,如果
df
是您的数据框:
table = df.pivot(index='Country',columns='Year',values='Value')
print (table)
This should shouldgive the desired output.
这应该应该得到所需要的输出。