如何摆放 pandas 数据框? [英] How to pivot a dataframe in Pandas?
本文介绍了如何摆放 pandas 数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
指标国家年度值
1安哥拉2005 6
2安哥拉2005 13
3安哥拉2005 10
4安哥拉2005 11
5安哥拉2005 5
1安哥拉2006 3
2安哥拉2006 2
3安哥拉2006 7
4安哥拉2006 3
5安哥拉2006 6
我希望最终结果如下所示:
国家年份1 2 3 4 5
安哥拉2005 6 13 10 11 5
安哥拉2006 3 2 7 3 6
我已经尝试使用大熊猫数据框架没有太多的成功cf。
print(df.pivot(columns ='Country','Year','Indicator',values ='Value '))
有关如何完成这项工作的任何想法?
谢谢
解决方案
您可以使用 pivot_table
/ p>
pd.pivot_table(df,values ='Value',index = ['Country','Year'],columns ='指标')。reset_index()
此输出:
指标国家年份1 2 3 4 5
0安哥拉2005 6 13 10 11 5
1安哥拉2006 3 2 7 3 6
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,
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.
print(df.pivot(columns = 'Country', 'Year', 'Indicator', values = 'Value'))
Any thoughts on how to accomplish this?
Thanks
解决方案
You can use 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
这篇关于如何摆放 pandas 数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文