Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a multilevel dataframe in pandas?

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

like image 630
hernanavella Avatar asked Nov 26 '16 15:11

hernanavella


1 Answers

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
like image 182
jezrael Avatar answered Sep 24 '22 23:09

jezrael