Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python / Pandas : concatenate two dataframes with multi index

Tags:

I have two dataframes with same index & columns. (x, y)

>>> x
    A   B
0  A0  B0
1  A1  B1

>>> y
    A   B
0  A2  B2
1  A3  B3

I found out how to concatenate two dataframes with multi-index as follows. (z)

>>> z = pd.concat([x, y], keys=['x', 'y'], axis=1)
>>> z
    x       y
    A   B   A   B
0  A0  B0  A2  B2
1  A1  B1  A3  B3

But I want to make the following format of dataframe (target )

>>> target
    A       B
    x   y   x   y
0  A0  A2  B0  B2
1  A1  A3  B1  B3

I have two questions

  1. Is there a nice way to get the 'target' dataframe directly from the x, y ?
  2. Is there a nice way to get the 'target' datafrme from z by changing the level of columns?

Thank you for considering my questions.

like image 390
hong Avatar asked Mar 07 '18 15:03

hong


1 Answers

Use swaplevel with sort_index:

z = pd.concat([x, y], keys=['x', 'y'], axis=1).swaplevel(0,1, axis=1).sort_index(axis=1)
print (z)
    A       B    
    x   y   x   y
0  A0  A2  B0  B2
1  A1  A3  B1  B3

For another answer is possible define dictionary of DataFrames for keys:

z = pd.concat({'x':x, 'y':y}, axis=1).swaplevel(0,1, axis=1).sort_index(axis=1)
like image 169
jezrael Avatar answered Sep 21 '22 13:09

jezrael