Converting a dataframe

Viewed 47
Pollutant Delhi London Paris
PM25 12 36 43
Ozone 120 34 42
NO2 192 35 12

I'm trying to convert a pandas DataFrame like the one above to the one below. Any help would be greatly appreciated! Thank you in advance.

Pollutant Level City
PM25 12 Delhi
Ozone 120 Delhi
NO2 192 Delhi
PM25 36 London
Ozone 34 London
NO2 35 London
PM25 43 Paris
Ozone 42 Paris
NO2 12 Paris
1 Answers

You can use pandas.melt() and utilise the different parameters correctly which is exactly what you need:

>>> df.melt(id_vars=['Pollutant'],value_name='Level',var_name='City')

  Pollutant    City  Level
0      PM25   Delhi     12
1     Ozone   Delhi    120
2       NO2   Delhi    192
3      PM25  London     36
4     Ozone  London     34
5       NO2  London     35
6      PM25   Paris     43
7     Ozone   Paris     42
8       NO2   Paris     12

value_name will give a name to the column where your values will be.

Same logic applies to var_name.

Related