0

There are a lot of similar questions, I tried them all but they are not working as I want them to. Let me explain:

I have two dataframes df1 and df2. Shape of df1 is (10000,10) and shape of df2 is (6000,3) .

Sample df1:

id      col1   col2    col3
sdfge    0       43     35
fgdge    0       34     353
dfgge   500     434     345
dsggh    43     34       345
bcbnn    23      0       86
gnncn    24      0       868
iopip    0       0       687

Sample df2

id      col1   col2  
sdfge    3453     453  
fgdge    23      345   
dsggh    44     357   
iopip    0      886  

Now I want to replace col1 and col2 value in df1 by using values from df2 (join by id.

1 Answer 1

1

Use map:

df1['col1'] = (df1['id'].map(df2.set_index('id')['col1'])
                        .fillna(df1['col1'], downcast='infer'))
df1['col2'] = (df1['id'].map(df2.set_index('id')['col2'])
                        .fillna(df1['col2'], downcast='infer'))

print(df1)
      id  col1  col2  col3
0  sdfge  3453   453    35
1  fgdge    23   345   353
2  dfgge   500   434   345
3  dsggh    44   357   345
4  bcbnn    23     0    86
5  gnncn    24     0   868
6  iopip     0   886   687
Sign up to request clarification or add additional context in comments.

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.