Reputation: 95
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.
Upvotes: 5
Views: 3144
Reputation: 323396
I just learn it recently 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
Upvotes: 2
Reputation: 863801
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)
Upvotes: 2