0

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?

Guilherme
  • 25
  • 4
  • Welcome to stack overflow! Please see the guide to [ask]. When asking a question, please search for other similar questions first (there are a zillion questions out there asking this exact thing). Also, if you have a unique question, make sure to show us what you've tried and exactly what's not working, including full tracebacks for errors. Ideally, frame the question using a [mre]. Thanks! – Michael Delgado Aug 24 '22 at 21:09
  • Hey @MichaelDelgado, thanks for the heads up... I just was having a hard time finding how to phrase a search for this answer, I did not knew about the stack and melt functions – Guilherme Aug 24 '22 at 21:30
  • sounds good. for future reference - the pandas docs have a whole section on [reshaping data](https://pandas.pydata.org/docs/user_guide/reshaping.html) – Michael Delgado Aug 24 '22 at 21:35

1 Answers1

0

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:])
Nuri Taş
  • 3,828
  • 2
  • 4
  • 22