Join dataframes by column values pandas

一世执手 提交于 2019-12-11 05:03:32

问题


I have two data frames df1 and df2 taken from different databases. Each item in the dataframes is identified by an id.

df1 = pd.DataFrame({'id':[10,20,30,50,100,110],'cost':[100,0,300,570,400,140]})

df2 = pd.DataFrame({'id':[10,23,30,58,100,110],'name':['a','b','j','d','k','g']})

there are some common products in both dataframes, in this case those with the ids: 10,30,100,110. I want to merge this information in one single dataframe, as this one:

df3 = pd.DataFrame({'id':[10,30,100,110],'name':['a','j','k','g'],'cost':[100,300,400,140]})

I was trying to do it with dictionaries and nested loops but I handling a rather big amount of data and it just take to long to do it that way.


回答1:


I think you can use merge, default parameter how='inner' is omited:

print (pd.merge(df1,df2,on='id'))
   cost   id name
0   100   10    a
1   300   30    j
2   400  100    k
3   140  110    g


来源:https://stackoverflow.com/questions/39703165/join-dataframes-by-column-values-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!