猿问

熊猫:合并两个具有相同值的不同键

我在下面有两个数据框:


dfA = pd.DataFrame([[3,"here",34]],columns = ["comp_id","mail","mean"])

dfB = pd.DataFrame([[23,3,"there"]], columns = ["alt","name_id","serv"])

dfA


        comp_id  mail  mean

   0          3 "here"   34

dfB


          alt  name_id   serv

   0       23        3  "there"

我想在 comp_id = name_id 上加入两个数据框


输出:


        mail  mean   alt     serv

 0     "here"   34    23   "there"

输出不应包括 comp_id 或 name_id。


关于如何执行此操作的任何建议?


慕的地10843
浏览 100回答 3
3回答

四季花海

merge与left_on和 一起使用right_on:pd.merge(dfA,dfB,left_on="comp_id", right_on = "name_id", how="inner")

千巷猫影

在为第一个数据框设置索引并从第二个数据框中删除列后使用合并dfA = dfA.set_index('comp_id')res = dfA.merge(dfB,left_index=True,right_on='name_id').drop('name_id',axis=1)print(res)

阿晨1998

合并后删除你的连接键:dfA.merge(dfB, left_on='comp_id', right_on='name_id').drop(['comp_id','name_id'], axis=1)输出:   mail  mean  alt   serv0  here    34   23  there
随时随地看视频慕课网APP

相关分类

Python
我要回答