Pandas: Multilevel column names

pandas, python

Solution

No need to create a list of tuples

Use: `pd.MultiIndex.from_product(iterables)`

import pandas as pd
import numpy as np

df = pd.Series(np.random.rand(3), index=["a","b","c"]).to_frame().T
df.columns = pd.MultiIndex.from_product([["new_label"], df.columns])

Resultant DataFrame:

  new_label                    
          a         b         c
0   0.25999  0.337535  0.333568

Pull request from Jan 25, 2014

Problem

`pandas` has support for multi-level column names: ``` >>> x = pd.DataFrame({'instance':['first','first','first'],'foo':['a','b','c'],'bar':rand(3)}) >>> x = x.set_index(['instance','foo']).transpose() >>> x.columns MultiIndex [(u'first', u'a'), (u'first', u'b'), (u'first', u'c')] >>> x instance first foo a b c bar 0.102885 0.937838 0.907467 ``` This feature is very useful since it allows multiple versions of the same dataframe to be appended 'horizontally' with the 1st level of the column names (in my example `instance`) distinguishing the instances. Imagine I already have a dataframe like this: ``` a b c bar 0.102885 0.937838 0.907467 ``` Is there a nice way to add another level to the column names, similar to this for row index: ``` x['instance'] = 'first' x.set_level('instance',append=True) ```

Original source

Related problems