How to Use Pandas Melt() Function

This short tutorial shows you how you can use melt() funtion in Pandas. It is often used when we need to change the format of dataframe to fit into a certain statistical functions.

Example 1 of Using melt()

import pandas as pd

City1= [6,2,3,4,5]
City2= [2,1,3,4,5]
City3= [4,1,2,4,5]

city_data = pd.DataFrame(
    {'City1': City1,
     'City2': City2,
     'City3': City3
    })

print(city_data)
   City1  City2  City3
0      6      2      4
1      2      1      1
2      3      3      2
3      4      4      4
4      5      5      5
city_data=city_data.melt( var_name="Cities", 
        value_name="Household_size")
print(city_data)
   Cities  Household_size
0   City1               6
1   City1               2
2   City1               3
3   City1               4
4   City1               5
5   City2               2
6   City2               1
7   City2               3
8   City2               4
9   City2               5
10  City3               4
11  City3               1
12  City3               2
13  City3               4
14  City3               5

Example 2 of Using melt()

import pandas as pd
City1= [6,2,3,4,5]
City2= [2,1,3,4,5]
City3= [4,1,2,4,5]
Housing_Type=["Apartment","Apartment","House","House","House"]

city_data = pd.DataFrame(
    {'Housing_Type':Housing_Type,
        'City1': City1,
     'City2': City2,
     'City3': City3
    })

print(city_data)
city_data=city_data.melt( 
    id_vars=["Housing_Type",],  
    var_name="Cities", 
        value_name="Household_size")
print(city_data)
  Housing_Type  City1  City2  City3
0    Apartment      6      2      4
1    Apartment      2      1      1
2        House      3      3      2
3        House      4      4      4
4        House      5      5      5
   Housing_Type Cities  Household_size
0     Apartment  City1               6
1     Apartment  City1               2
2         House  City1               3
3         House  City1               4
4         House  City1               5
5     Apartment  City2               2
6     Apartment  City2               1
7         House  City2               3
8         House  City2               4
9         House  City2               5
10    Apartment  City3               4
11    Apartment  City3               1
12        House  City3               2
13        House  City3               4
14        House  City3               5