user3249690
user3249690

Reputation: 15

How to select column values in a data frame using column values of other data frame

Suppose that you create the next python pandas data frames:

In[1]: print df1.to_string()
    ID value
0   1     a
1   2     b
2   3     c
3   4     d


In[2]: print df2.to_string()
      Id_a  
0     1            
1     4            
2     2            
3     3            
4     4            
5     2       

How can I update df2, such that will look like:

In[2]: print df2.to_string()
      Id_a  value 
0     1     a       
1     4     d       
2     2     b       
3     3     c       
4     4     d       
5     2     b

In other words, I would like to add an extra column based in the values of df1.

Thanks

Upvotes: 1

Views: 140

Answers (2)

Bij
Bij

Reputation: 301

The following should work:

import pandas as pd
df1 = pd.DataFrame({"ID":[1,2,3,4], "value": ["a","b","c","d"]})
df2 = pd.DataFrame({"Id_a": [1,4,2,3,4,2]})

merged_df = pd.merge(df2, df1, left_on="Id_a", right_on="ID")
print merged_df

Upvotes: 0

Alvaro Fuentes
Alvaro Fuentes

Reputation: 17485

Try this:

pd.merge(df1.rename(columns={'ID':'Id_a'}),df2,on='Id_a')

Upvotes: 1

Related Questions