Examples

In [2]:
import numpy as np
import pandas as pd
In [5]:
df = pd.DataFrame({'P': {0: 'p', 1: 'q', 2: 'r'},
                   'Q': {0: 2, 1: 4, 2: 6},
                   'R': {0: 3, 1: 5, 2: 7}})
df
Out[5]:
P Q R
0 p 2 3
1 q 4 5
2 r 6 7
In [6]:
pd.melt(df, id_vars=['P'], value_vars=['Q'])
Out[6]:
P variable value
0 p Q 2
1 q Q 4
2 r Q 6
In [7]:
pd.melt(df, id_vars=['P'], value_vars=['Q', 'R'])
Out[7]:
P variable value
0 p Q 2
1 q Q 4
2 r Q 6
3 p R 3
4 q R 5
5 r R 7

The names of ‘variable’ and ‘value’ columns can be customized:

In [8]:
pd.melt(df, id_vars=['P'], value_vars=['Q'],
        var_name='myVarname', value_name='myValname')
Out[8]:
P myVarname myValname
0 p Q 2
1 q Q 4
2 r Q 6

If you have multi-index columns:

In [9]:
df.columns = [list('PQR'), list('STU')]
df
Out[9]:
P Q R
S T U
0 p 2 3
1 q 4 5
2 r 6 7
In [10]:
pd.melt(df, col_level=0, id_vars=['P'], value_vars=['Q'])
Out[10]:
P variable value
0 p Q 2
1 q Q 4
2 r Q 6
In [11]:
pd.melt(df, id_vars=[('P', 'S')], value_vars=[('Q', 'T')])
Out[11]:
(P, S) variable_0 variable_1 value
0 p Q T 2
1 q Q T 4
2 r Q T 6