Python / Pandas: combine two data frames with multiple indexes

I have two data frames with the same index and columns. (x, y)

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

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

I learned how to concatenate two data frames with a multi-index as follows. (D)

>>> 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 dataframe (target) format

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

I have two questions

  • Is there a good way to get the “target” dataframe directly from x, y?
  • Is there a good way to get the "target" datafrme from z by changing the column level?

Thank you for considering my questions.

+4
source share
2 answers

Use swaplevelwith 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, you can define dictionary of DataFramesfor the keys:

z = pd.concat({'x':x, 'y':y}, axis=1).swaplevel(0,1, axis=1).sort_index(axis=1)
+2
source

I recently found out about this reorder_levels:-)

pd.concat([x,y],keys=['x','y'],axis=1).reorder_levels([1,0],axis=1).sort_index(axis=1)
Out[449]: 
    A       B    
    x   y   x   y
0  A0  A2  B0  B2
1  A1  A3  B1  B3
+2
source

Source: https://habr.com/ru/post/1694604/


All Articles