Transform pandas dataframe structure

Question:

I have a dataframe in the following format:

    Year    United Kingdom  Canada
0   1880    0.13    0.00
1   1890    0.16    0.00
2   1900    0.29    0.00
3   1910    0.32    0.00
4   1920    0.56    0.01

I wish to transform it to:

    Year    Country         value
0   1880    United Kingdom  0.13    
1   1890    United Kingdom  0.16
2   1900    United Kingdom  0.29    
3   1910    United Kingdom  0.32
4   1920    United Kingdom  0.56
5   1880    Canada          0.00
6   1890    Canada          0.00 
...

I tried using transpose and reset_index but couldn’t find the correct solution. I there an simple way to do this or I would need to create a complete new dataframe?

Asked By: Guilherme

||

Answers:

Try:

df = df.set_index('Year').stack().reset_index()
df.columns = ['Year', 'Country', 'value']

or:

df.melt(id_vars='Year', value_vars=df.columns[1:])
Answered By: Nuri Taş
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.