1 回答
TA贡献1806条经验 获得超5个赞
您可以将join
ormerge
与swaplevel()
or 一起使用reorder_levels
。然后使用.sort_index()
和 传递axis=1
来按索引列排序。
.join()
当您像这样对索引进行合并时会更好。.swaplevel()
当有两个级别时更好(如本例),而当.reorder_levels()
有 3 个或更多级别时更好。
以下是这些方法的 4 种组合。对于这个具体的例子,我认为.join()
/.swaplevel()
是最简单的(参见最后一个例子):
df3 = (df1.reorder_levels([1,0],axis=1)
.join(df2.reorder_levels([1,0],axis=1), rsuffix='_2')
.reorder_levels([1,0],axis=1).sort_index(axis=1, level=[0, 1]))
df3
Out[1]:
a b c
w w_2 x x_2 w w_2 x x_2 w w_2 x x_2
0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
1 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
2 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN
3 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN
df3 = (pd.merge(df1.reorder_levels([1,0],axis=1),
df2.reorder_levels([1,0],axis=1),
how='left', left_index=True, right_index=True, suffixes = ('', '_2'))
.reorder_levels([1,0],axis=1).sort_index(axis=1, level=[0, 1]))
df3
Out[2]:
a b c
w w_2 x x_2 w w_2 x x_2 w w_2 x x_2
0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
1 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
2 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN
3 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN
df3 = (pd.merge(df1.swaplevel(axis=1),
df2.swaplevel(axis=1),
how='left', left_index=True, right_index=True, suffixes = ('', '_2'))
.swaplevel(axis=1).sort_index(axis=1, level=[0, 1]))
df3
Out[3]:
a b c
w w_2 x x_2 w w_2 x x_2 w w_2 x x_2
0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
1 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
2 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN
3 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN
df3 = (df1.swaplevel(i=0,j=1, axis=1)
.join(df2.swaplevel(axis=1), rsuffix='_2')
.swaplevel(axis=1).sort_index(axis=1, level=[0, 1]))
df3
Out[4]:
a b c
w w_2 x x_2 w w_2 x x_2 w w_2 x x_2
0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
1 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
2 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN
3 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN 1.0 NaN
添加回答
举报