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

How to melt a dataframe into a long form?

I have the following dataframe

recycling 1 metric tonne (1000 kilogram) per waste type  Unnamed: 1 Unnamed: 2     Unnamed: 3       Unnamed: 4      Unnamed: 5
0    1 barrel oil is approximately 159 litres of oil       NaN          NaN            NaN              NaN             NaN
1                NaN                                       NaN          NaN            NaN              NaN             NaN
2                material                                  Plastic    Glass     Ferrous Metal     Non-Ferrous Metal     Paper
3               energy_saved                               5774 Kwh   42 Kwh         642 Kwh          14000 Kwh        4000 kWh
4               crude_oil saved                            16 barrels   NaN        1.8 barrels        40 barrels      1.7 barrels

For reference look at the image:
enter image description here
What I want to do is to get the rows 2, 3, 4 into cols in a new dataframe. It should be looking some like this..

  material   energy_saved   crude_oil saved
  plastic     5774Kwh         16 barrels
  Glass        42 Kwh          NaN
  ...           ...            ...

I tried using .melt but it was not working.
If you notice, the col name and its values are in a single row. I just want them to be in a new data frame as col and value.

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 :

IIUC, is it just:

out = df.loc[[2,3,4],:].T.reset_index(drop=True)
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