python/pandas: how to combine two dataframes into one with hierarchical column index?

This is a doc example: http://pandas.pydata.org/pandas-docs/stable/merging.html#more-concatenating-with-group-keys

In [9]: df1 = pd.DataFrame(np.random.randn(3,2),columns=list('AB'),index=pd.date_range('20000101',periods=3))

In [10]: df2 = pd.DataFrame(np.random.randn(3,2),columns=list('AB'),index=pd.date_range('20000101',periods=3))

In [11]: df1
Out[11]: 
                   A         B
2000-01-01  0.129994  1.189608
2000-01-02 -1.126812  1.087617
2000-01-03 -0.930070  0.253098

In [12]: df2
Out[12]: 
                   A         B
2000-01-01  0.535700 -0.769533
2000-01-02 -1.698531 -0.456667
2000-01-03  0.451622 -1.500175

In [13]: pd.concat(dict(df1 = df1, df2 = df2),axis=1)
Out[13]: 
                 df1                 df2          
                   A         B         A         B
2000-01-01  0.129994  1.189608  0.535700 -0.769533
2000-01-02 -1.126812  1.087617 -1.698531 -0.456667
2000-01-03 -0.930070  0.253098  0.451622 -1.500175

Leave a Comment