31

I have two dataframes which look like this:

>>> df1
              A    B
2000-01-01  1.4  1.4
2000-01-02  1.7 -1.9
2000-01-03 -0.2 -0.8

>>> df2
              A    B
2000-01-01  0.6 -0.3
2000-01-02 -0.4  0.6
2000-01-03  1.1 -1.0

How can I make one dataframe out of this two with hierarchical column index like below?

            df1       df2
              A    B    A    B
2000-01-01  1.4  1.4  0.6 -0.3
2000-01-02  1.7 -1.9 -0.4  0.6
2000-01-03 -0.2 -0.8  1.1 -1.0
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
  • 2
    http://pandas.pydata.org/pandas-docs/dev/merging.html#more-concatenating-with-group-keys, just pass a dict of your keys to pieces to concat – Jeff Apr 13 '13 at 17:01

1 Answers1

29

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
Zulan
  • 21,896
  • 6
  • 49
  • 109
Jeff
  • 125,376
  • 21
  • 220
  • 187
  • surprised me it takes dfs as keys – Mr_and_Mrs_D Jul 11 '19 at 15:15
  • If you're just interested in adding the dataframe name as first level: pd.concat(dict(df1 = df1), axis=1) – José Vallejo Dec 20 '19 at 09:32
  • 2
    @Mr_and_Mrs_D, it does not take `pd.DataFrames` as keys. The built-in `dict()` constructor, which allows simple string keys to be set using keyword arguments. The example from the python docs is: `dict(sape=4139, guido=4127, jack=4098)`. This is why `'df1'` and `'df2'` are keys after calling `pd.concat()`. – Rich Inman Mar 20 '20 at 17:04