Examples

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

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

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

For multi-index columns:

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