2

I have data set having columns

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]})

I want to pivot this table with three columns

Country    
Year    
Value

How should I extend my python code for the output above?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

3

You want 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
...
yatu
  • 86,083
  • 12
  • 84
  • 139