0

I have two data-frames where df1 looks like:

id  Status Colour 
 1      On   Blue
19      On    Red
 4      On  Green
56      On   Blue

df2 looks like

id   Status
19      Off
 4     Even

I am trying to replace the Status in df1 with the Status in df2 if the id is present in both data-frames so my resulting data-frame looks like:

id  Status  Colour 
 1      On    Blue
19     Off     Red
 4    Even   Green
56      On    Blue 

I can identify the field in df1 that I want to change using:

df1.loc[df1['id'].isin(df2['id']), 'Status'] = referenced date

But I can't see how to identify the field in df2 to pass to df1 (the part to the right of the above equals sign)

How can I do this?

1
  • Have you tried a merge? Commented Aug 2, 2019 at 11:38

2 Answers 2

1

Use Series.map with replace non matched missing values by fillna:

df1['Status'] = df1['id'].map(df2.set_index('id')['Status']).fillna(df1['Status'])
print (df1)
   id Status Colour
0   1     On   Blue
1  19    Off    Red
2   4   Even  Green
3  56     On   Blue
Sign up to request clarification or add additional context in comments.

Comments

0

try like below

result = df1.merge(df2, on='id', how='left')
result['status'] = result['status_y'].fillna(result['status_x'])
result.drop(['status_x','status_y'],axis=1,inplace=True)


   color  id status
0   blue   1     on
1    red  19    off
2  green   4   even
3   blue  56     on

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.