Python Question

Join dataframes by column values pandas

I have two data frames

taken from different databases. Each item in the dataframes is identified by an

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.


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