Pandas Merge -如何合并不同的索引列



我试图在列上合并两个不同的dataframe,名称不同,但值是相同的。例如,

df1

name subject result
0   Kim       c   pass
1   Lee  python   pass
2  Choi       c   fail

df2

name language  score
0    Kim        c     95
1  Hwang     java     85
2    Lee   python     97
3   Park   python     80

如果我运行pd.merge(df1, df2, left_on='subject', right_on='language'),那么我得到

#2 Merge stu1, stu2 by key value
name_x subject result name_y language  score
0    Kim       c   pass    Kim        c     95
1   Choi       c   fail    Kim        c     95
2    Lee  python   pass    Lee   python     97
3    Lee  python   pass   Park   python     80

but在列'subject'和'language'中,我希望它们之间只有一列。他们是多余的。

谢谢!

您可以尝试重命名该列:

out=pd.merge(df1, df2.rename(columns={'language':'subject'}),on='subject')

删除合并后的列:

out=pd.merge(df1, df2, left_on='subject', right_on='language').drop(columns='language')

最新更新