KGBeans KGBeans - 3 months ago 6
Python Question

Iterating through two pandas dataframes and appending data from one dataframe to the other

I have two pandas data-frames that look like this:

data_frame_1:

index un_id city
1 abc new york
2 def atlanta
3 gei toronto
4 lmn tampa


data_frame_2:

index name un_id
1 frank gei
2 john lmn
3 lisa abc
4 jessica def


I need to match names to cities via the un_id column either in a new data-frame or an existing data-frame. I am having trouble figuring out how to iterate through one column, grab the un_id, iterate through the other un_id column in the other data-frame with that un_id, and then append the information needed back to the original data-frame.

Answer

use pandas merge:

In[14]:df2.merge(df1,on='un_id')
Out[14]: 
      name un_id      city
0    frank   gei   toronto
1     john   lmn     tampa
2     lisa   abc  new york
3  jessica   def   atlanta
Comments