使用python的数据透视表

时间:2019-03-28 16:23:28

标签: python pandas dataframe pivot-table

我的数据集包含列

Country  
2001    
2002    
2003
...


import python as pd

df=pd.DataFrame({"country":['India','UK','France','US','Nepal'],'2001':[1,2,3,4,5],
               '2002':[1,2,3,4,5],'2003':[1,2,3,4,5],'2004':[1,2,3,4,5],
               '2005':[1,2,3,4,5],'2006':[1,2,3,4,5]})

我想用三列透视表

Country    
Year    
Value

如何为上面的输出扩展python代码?

1 个答案:

答案 0 :(得分:3)

您想要DataFrame.melt

df.melt(id_vars='country', var_name='Year')

   country  Year  value
0    India  2001      1
1       UK  2001      2
2   France  2001      3
3       US  2001      4
4    Nepal  2001      5
5    India  2002      1
6       UK  2002      2
7   France  2002      3
8       US  2002      4
9    Nepal  2002      5
10   India  2003      1
...