How to create a multilevel dataframe in pandas?

10,512

Solution 1

One option is to use MultiIndex() to construct the columns level for A and B and then concatenate them:

import pandas as pd
A.columns = pd.MultiIndex.from_product([['A'], A.columns])
B.columns = pd.MultiIndex.from_product([['B'], B.columns])
pd.concat([A, B], axis = 1)

#           A       B
#           a   b   a   b
#2016-11-21 2   1   3   0
#2016-11-22 3   4   1   0
#2016-11-23 5   2   1   6
#2016-11-24 6   3   1   5
#2016-11-25 6   3   0   2

Solution 2

You can use concat with parameter keys:

df = pd.concat([A, B], axis = 1, keys=(list('AB')))
print (df)
            A     B   
            a  b  a  b
2016-11-21  2  1  3  0
2016-11-22  3  4  1  0
2016-11-23  5  2  1  6
2016-11-24  6  3  1  5
2016-11-25  6  3  0  2
Share:
10,512
hernanavella
Author by

hernanavella

Pa'que zapatos si no hay casa...

Updated on June 11, 2022

Comments

  • hernanavella
    hernanavella almost 2 years

    Given two different df's:

    'A'

                a  b         
    2016-11-21  2  1
    2016-11-22  3  4
    2016-11-23  5  2 
    2016-11-24  6  3 
    2016-11-25  6  3
    

    'B'

                a  b         
    2016-11-21  3  0
    2016-11-22  1  0
    2016-11-23  1  6 
    2016-11-24  1  5 
    2016-11-25  0  2
    

    How can I create a 'multilevel' dataframe of this shape:

    'C'

                A     B
                a  b  a  b           
    2016-11-21  2  1  3  0
    2016-11-22  3  4  1  0
    2016-11-23  5  2  1  6
    2016-11-24  6  3  1  5
    2016-11-25  6  3  0  2
    

    *index is a 'datatime' object

    Thanks

  • Alex
    Alex over 7 years
    Why not just use MultiIndex.from_product() once on the resultant df? result = pd.concat([A, B], axis=1) result.columns = pd.MultiIndex.from_product([('A', 'B'), A.columns])
  • Alex
    Alex over 7 years
    Also why isn't the first level of your columnar multi-index aligned the way it is in jezrael's answer?
  • Psidom
    Psidom over 7 years
    If the two data frames have different dimensions or different column names, use MultiIndex on the result won't work. The first level is aligned the same way as jezrael's answer, if you check the answer. I probably have indented differently here.
  • alphazwest
    alphazwest over 2 years
    This works great for my, admittedly simple, use-case.