Search code examples
pythonpandasdataframemulti-index

Concatenate two DataFrames into one MultiIndex sharing the same DateTimeIndex


I could concatenate two DataFrames df1 & df2 into one df but I somehow could not get the "stack" structure that I need - see attached image.

How do I get df1 & df2 to combine to share one DateTimeIndex like the one in a "stack" structure?

df1 & df2 df


Solution

  • I think you need to_frame:

    df = pd.DataFrame({'AAPL':[1,3,4],
                       'GOOG_L':[6,7,8]}, index=pd.date_range('2012-01-01', periods=3))
    print (df)
                AAPL  GOOG_L
    2012-01-01     1       6
    2012-01-02     3       7
    2012-01-03     4       8
    
    df1 = df.stack().to_frame('col')
    print (df1)
                       col
    2012-01-01 AAPL      1
               GOOG_L    6
    2012-01-02 AAPL      3
               GOOG_L    7
    2012-01-03 AAPL      4
               GOOG_L    8
    
    df2 = df.unstack().to_frame('col')
    print (df2)
                       col
    AAPL   2012-01-01    1
           2012-01-02    3
           2012-01-03    4
    GOOG_L 2012-01-01    6
           2012-01-02    7
           2012-01-03    8