我有一个 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
我希望最终的结果是这样的:
Country Year 1 2 3 4 5
Angola 2005 6 13 10 11 5
Angola 2006 3 2 7 3 6
我尝试使用 pandas 数据框但没有取得太大成功。
print(df.pivot(columns = 'Country', 'Year', 'Indicator', values = 'Value'))
关于如何实现这一目标有什么想法吗?
您可以使用pivot_table
:
pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index()
这输出:
Indicator Country Year 1 2 3 4 5
0 Angola 2005 6 13 10 11 5
1 Angola 2006 3 2 7 3 6
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)