pd.merge(pd.merge(df1,df2,'left',on='year',suffixes=['_a','_b']),
df3,'left',on='year',suffixes=['','_c'])
另一种方法:
源 DF:
In [68]: d1
Out[68]:
col1 col2 col3
0 1 2 3
1 4 5 6
In [69]: d2
Out[69]:
col1 col2 col3
0 11 12 13
1 14 15 16
In [70]: d3
Out[70]:
col1 col2 col3
0 21 22 23
1 24 25 26
让我们创建一个 DF 列表:
In [71]: dfs = [d1,d2,d3]
以及后缀列表:
In [73]: suffixes = ['_a','_b','_c']
现在我们可以像下面这样一步合并它们:
In [74]: pd.concat([df.add_suffix(suffixes[i]) for i,df in enumerate(dfs)], axis=1)
Out[74]:
col1_a col2_a col3_a col1_b col2_b col3_b col1_c col2_c col3_c
0 1 2 3 11 12 13 21 22 23
1 4 5 6 14 15 16 24 25 26
简短说明:在列表推导中,我们正在生成一个包含已重命名列的 DF 列表:
In [75]: [suffixes[i] for i,df in enumerate(dfs)]
Out[75]: ['_a', '_b', '_c']
In [76]: [df.add_suffix(suffixes[i]) for i,df in enumerate(dfs)]
Out[76]:
[ col1_a col2_a col3_a
0 1 2 3
1 4 5 6, col1_b col2_b col3_b
0 11 12 13
1 14 15 16, col1_c col2_c col3_c
0 21 22 23
1 24 25 26]