2

I basically have this

   first    
0   bar 
1   bar 
2   foo 
3   foo 
   bar foo
0   a   b

I want to insert value in dataframe 2 to dataframe 1, so the final result should be something like this

   first    
0   a   
1   a   
2   b   
3   b   

2 Answers 2

2

You can simply use replace like so:

>>> df1.replace(df2.transpose()[0])
    first
0     a
1     a
2     b
3     b

If you want to check efficiency:

%timeit df1.replace(df2.transpose()[0])
711 µs ± 18.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Sign up to request clarification or add additional context in comments.

1 Comment

good answer, you propably could shorten it like this: df1.replace(df2.T)[0])
1

You can use join on a transposed df2:

df1.set_index('first').join(df2.T)

Out[11]:
     0
bar  a
bar  a
foo  b
foo  b

Or with a dictionary:

df1['first'].map(df2.T.to_dict()[0])

Out[17]: 
0    a
1    a
2    b
3    b
Name: first, dtype: object

Or with merge:

df1.merge(df2.T.reset_index(), left_on=['first'], right_on=['index'])

  first index  0
0   bar   bar  a
1   bar   bar  a
2   foo   foo  b
3   foo   foo  b

Comments

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.