并排合并 Pandas 个数据框列

Merged Pandas dataframe columns side by side

如果我如图所示合并两个数据帧

df1=pd.DataFrame({"Name": ["Alex","Ben","Cat","Dog"],'A':[1,2,3,3],'B':[2,3,4,4]})
df2=pd.DataFrame({"Name": ["Alex","Ben","Cat","Dog"],'A':[2,3,4,4],'B':[1,2,3,3]})

df_merged = pd.merge(df1,df2, on = "Name", suffixes= ["L","R"])

这就是我的合并数据框 df_merged 的样子

Name    AL  BL  AR  BR
0   Alex 1  1   2   2   
1   Ben  2  3   3   2
2   Cat  3  4   4   3
3   Dog  3  4   4   3

但是有没有办法让 df_merged 看起来像

Name    AL AR BL BR
0   Alex 1  2  1  2 
1   Ben  2  3  3  2
2   Cat  3  4  4  3
3   Dog  3  4  4  3

其中数据框的列彼此相邻。

这只是出于美观原因而不是其他任何原因的兴趣。我在任何地方都找不到它的例子。

您需要更改列的顺序,这里是动态方法:

#get all columns names in both df, removed Name used for key in merge
same = df1.columns.intersection(df2.columns, sort=False).difference(['Name'])

#generate columns in order
cols = [f'{a}{b}' for a in same for b in ['L','R']]

#get different like `cols` from merged df and add cols in order
order = df_merged.columns.difference(cols, sort=False).union(cols, sort=False)

#changed order by list
df = df_merged[order]
print (df)
   Name  AL  AR  BL  BR
0  Alex   1   2   2   1
1   Ben   2   3   3   2
2   Cat   3   4   4   3
3   Dog   3   4   4   3

手动方法:

df = df_merged[['Name', 'AL', 'AR', 'BL', 'BR']]