Melt with Pandas


In [3]:
import pandas as pd

In [5]:
df = pd.DataFrame([
    {'first': 'john', 'last': 'smith', 'height': '180', 'weight': '80'},
    {'first': 'jane', 'last': 'doe', 'height': '160', 'weight': '50'}
])
df.head()


Out[5]:
first height last weight
0 john 180 smith 80
1 jane 160 doe 50

In [6]:
pd.melt(df, id_vars=['first', 'last'])


Out[6]:
first last variable value
0 john smith height 180
1 jane doe height 160
2 john smith weight 80
3 jane doe weight 50

In [7]:
pd.melt(df, id_vars=['first'])


Out[7]:
first variable value
0 john height 180
1 jane height 160
2 john last smith
3 jane last doe
4 john weight 80
5 jane weight 50

Here's a rel-life example.