How to use pd.melt method in Pandas

pd.melt method in Pandas gathers columns into rows, lets understand pd.melt with an example.

Create Dataframe


import pandas as pd

a1 = [30,45, 56, 78, 89, 90]
b1 = ["abc", "bcd", "aaa", "ghj", "hgf" , "kgj"]
c1 = [45, 65, 45 , 67, 56, 68]

df = pd.DataFrame({
    "col1":a1,
    "col2":b1,
    "col3":c1})

print(df)

Output:


   col1 col2  col3
0    30  abc    45
1    45  bcd    65
2    56  aaa    45
3    78  ghj    67
4    89  hgf    56
5    90  kgj    68

Apply pd.melt on created Dataframe


df2 = pd.melt(df)

print(df2)

Output:


   variable value
0      col1    30
1      col1    45
2      col1    56
3      col1    78
4      col1    89
5      col1    90
6      col2   abc
7      col2   bcd
8      col2   aaa
9      col2   ghj
10     col2   hgf
11     col2   kgj
12     col3    45
13     col3    65
14     col3    45
15     col3    67
16     col3    56
17     col3    68

Follow US on Twitter: