如何在 Pandas 中透视数据框? [英] How to pivot a dataframe in Pandas?

查看:33
本文介绍了如何在 Pandas 中透视数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 csv 格式的表格,看起来像这样.我想转置表格,使指标名称列中的值成为新列,

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

我曾尝试使用 Pandas 数据框,但收效甚微.

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?

谢谢

推荐答案

你可以使用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

这篇关于如何在 Pandas 中透视数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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