Pandas:在选定的列上加入数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38188420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:30:53  来源:igfitidea点击:

Pandas: Join dataframes on selected columns

pythonpandasjoinmerge

提问by Manu Sharma

I have two data frames as following

我有两个数据框如下

 Data Set A
 ID type   msg 
 1  High   Lets do
 2  Low    whats it 
 3  Medium thats it

 Data Set B 
 ID  Accounttype
 2   Facebook
 3   Linkedin

How can I get an updated table with help of join in pandas, it should look like an

如何在加入Pandas的帮助下获得更新的表格,它应该看起来像

Updated DatasetA 

ID Account    type  msg
 1            High   Lets do
 2  Facebook  Low    whats it 
 3  Linkedin  Medium thats it

I can easily do it in SQL with Update and inner join, how to perform it in pandas, I tried to do it, but most of the operations for append/ merge. Any help will be appreciated

我可以使用更新和内部联接在 SQL 中轻松完成,如何在 Pandas 中执行它,我尝试这样做,但大多数附加/合并操作。任何帮助将不胜感激

回答by Merlin

Try this:

尝试这个:

 df4

#   ID    type      msg
 #   0   1    High   Letsdo
 #   1   2     Low  whatsit
 #   2   3  Medium  thatsit

df3:

 #          ID Accounttype  xxx
 #       0   2    Facebook   24
 #       1   3    Linkedin   44

   df4.merge(df3[['ID','Accounttype']],how='left').fillna("")

#    ID    type      msg Accounttype
# 0   1    High   Letsdo            
# 1   2     Low  whatsit    Facebook
# 2   3  Medium  thatsit    Linkedin

回答by Manu Sharma

Seems there is no direct way to do it, so following is suggested

似乎没有直接的方法来做到这一点,所以建议以下

 a=b.merge(account,how='left',on='ID')

create a list of columns you want in final data set

在最终数据集中创建您想要的列列表

 list=['ID','Account','type','msg'] 

 final=a[[col for col in list if col in b.columns]]

It will give you only desired columns after the left join

左连接后它只会给你想要的列