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