2

With these two data frames

df1 = pd.DataFrame({'c1':['a','b','c','d'],'c2':[10,20,10,22]})
df2 = pd.DataFrame({'c3':['e','f','a','g','b','c','r','j','d'],'c4':[1,2,3,4,5,6,7,8,9]})

I'm trying to add the values of c4 to df1 for only the elements in c3 that are also present in c1:

>>> df1
  c1  c2  c4
  a   10  3  
  b   20  5
  c   10  6
  d   22  9

Is there a simple way of doing this in pandas?

UPDATE:

If

df2 = pd.DataFrame({'c3':['e','f','a','g','b','c','r','j','d'],'c4':[1,2,3,4,5,6,7,8,9]},'c5':[10,20,30,40,50,60,70,80,90])

how can I achieve this result?

>>> df1
  c1  c2  c4  c5
  a   10  3   30  
  b   20  5   50
  c   10  6   60
  d   22  9   90

Doing:

>>> df1['c1'].map(df2.set_index('c3')['c4','c5'])

gives me a KeyError

2
  • You should not modify your question and change your requirements, if you have a new question then post a new question, anyway df1.merge(df2, left_on='c1', right_on='c3').drop('c3', axis=1) is what you want Commented Jul 31, 2015 at 15:33
  • @EdChum: Ok, I'll do it next time. Many thanks again for your help! Commented Jul 31, 2015 at 15:42

1 Answer 1

2

You can call map on df2['c4'] after setting the index on df2['c3'], this will perform a lookup:

In [239]:
df1 = pd.DataFrame({'c1':['a','b','c','d'],'c2':[10,20,10,22]})
df2 = pd.DataFrame({'c3':['e','f','a','g','b','c','r','j','d'],'c4':[1,2,3,4,5,6,7,8,9]})
df1['c4'] = df1['c1'].map(df2.set_index('c3')['c4'])
df1

Out[239]:
  c1  c2  c4
0  a  10   3
1  b  20   5
2  c  10   6
3  d  22   9
Sign up to request clarification or add additional context in comments.

2 Comments

Is it actually possible to call "map" on more than one column? I have updated my example.
To answer your question, no it won't work that way, for your updated example use merge

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.