Examples
import numpy as np
import pandas as pd
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
df.melt(id_vars=['P'], value_vars=['Q'])
df.melt(id_vars=['P'], value_vars=['Q', 'R'])
The names of ‘variable’ and ‘value’ columns can be customized:
df.melt(id_vars=['P'], value_vars=['Q'],
var_name='myVarname', value_name='myValname')
For multi-index columns:
df.columns = [list('PQR'), list('STV')]
df
df.melt(col_level=0, id_vars=['P'], value_vars=['Q'])
df.melt(id_vars=[('P', 'S')], value_vars=[('Q', 'T')])