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
Thank you for considering my questions.
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With