Creating Multi-Indexed and Named DataFrame in Pandas in Statement

Sometimes you want to create a complex multi-indexed DataFrame with named axes in Pandas in just one line. Here's one way how:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(12).reshape(4,3),
                 index=pd.MultiIndex.from_arrays([['a','a','b','b'],
                                                  [1,2,1,2]],
                                                  names=['AAAAA','BBBBBB']),
                 columns=pd.MultiIndex.from_arrays([['VAR-A','VAR-A', 'VAR-B'],
                                                    ['var-a','var-b', 'var-c']],
                                                    names=['XXXX','YYYY']))

The DataFrame constructor does not have the parameter for passing the names for levels in axes, therefore you have to use the MultiIndex constructor that does.

The result is the below DataFrame.

XXXX          VAR-A         VAR-B
YYYY          var-a  var-b  var-c
AAAAA BBBBBB                     
a     1           0      1      2
      2           3      4      5
b     1           6      7      8
      2           9     10     11

F & P