为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地10843 2023-04-11 15:01:34
我在下面有两个数据框: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"   34dfB          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。关于如何执行此操作的任何建议?
查看完整描述

3 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

mergeleft_on和 一起使用right_on

pd.merge(dfA,dfB,left_on="comp_id", right_on = "name_id", how="inner")


查看完整回答
反对 回复 2023-04-11
?
千巷猫影

TA贡献1829条经验 获得超7个赞

在为第一个数据框设置索引并从第二个数据框中删除列后使用合并


dfA = dfA.set_index('comp_id')

res = dfA.merge(dfB,left_index=True,right_on='name_id').drop('name_id',axis=1)

print(res)


查看完整回答
反对 回复 2023-04-11
?
阿晨1998

TA贡献2037条经验 获得超6个赞

合并后删除你的连接键:


dfA.merge(dfB, left_on='comp_id', right_on='name_id').drop(['comp_id','name_id'], axis=1)

输出:


   mail  mean  alt   serv

0  here    34   23  there


查看完整回答
反对 回复 2023-04-11
  • 3 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信