Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform pandas dataframe structure

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading