1

I would like to assign values to a column based on the values in another dataframe.

For example, in the example below the values in column B of df2 should be equal to the df['B'] value in df1 where df1['A'] = df2['A']. The output should then be the same as df3.

> import pandas as pd  
> import numpy as np
> 
> df1 = pd.DataFrame({'A':[1,2,3],'B':["req 1", "req 2","req 3"]})
> df2 = pd.DataFrame({'A':[2,1,7],'B':[np.nan,np.nan,np.nan]})
> df3= pd.DataFrame({'A':[2,1,7],'B':["req 2", "req 1",np.nan]})

Could somebody help me with this?

2 Answers 2

3

You can achieve that with fillna():

out = df2.set_index('A').fillna(df1.set_index('A')).reset_index()
>>> out

   A      B
0  2  req 2
1  1  req 1
2  7    NaN
>>> df3
 
   A      B
0  2  req 2
1  1  req 1
2  7    NaN
Sign up to request clarification or add additional context in comments.

Comments

3

You can do merge to achieve this -

df2 = df2.merge(df1, on='A', how='left').drop('B_x', axis=1).rename(columns={"B_y": 'B'})

output -


    A   B
0   2   req 2
1   1   req 1
2   7   NaN

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.