richie
richie

Reputation: 18638

Reshape Dataframe columns to rows

I have a DataFrame that looks like this;

Year   US  China   Russia
2007   NaN   45      12
2008   12    22       4
2009   12    NaN     41

I want it reshaped to look like this;

Year Country Value
2007  US      NaN
2007  China    45
2007  Russia   12
2008  US       12
2008  China    22
2008  Russia   4
2009  US       12
2009  China   NaN
2009  Russia    41

How do I do that?

Upvotes: 1

Views: 1357

Answers (1)

richie
richie

Reputation: 18638

Just came across the pd.melt() function.

It works like this;

pd.melt(data,id_vars=['Year']).sort('Year')

Upvotes: 4

Related Questions