How to pivot a dataframe in Pandas? [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-17 07:28:37

问题


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


回答1:


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



回答2:


This is a guess: it's not a ".csv" file, but a Pandas DataFrame imported from a '.csv'.

To pivot this table you want three arguments in your Pandas "pivot". e.g., if df is your dataframe:

table = df.pivot(index='Country',columns='Year',values='Value')  
print (table)

This should should give the desired output.



来源:https://stackoverflow.com/questions/28337117/how-to-pivot-a-dataframe-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!