简体   繁体   English

用另一个数据帧中的数据替换一个数据帧中的数据

[英]Replace data in a data-frame with data from another data-frame

I have two data-frames where df1 looks like:我有两个数据框,其中df1看起来像:

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

df2 looks like df2看起来像

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:我想,以取代Statusdf1Statusdf2如果id存在于两个数据帧,所以我得到的数据帧的格式如下:

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中要更改的字段:

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)但我看不到如何识别df2的字段以传递给df1 (上述等号右侧的部分)

How can I do this?我怎样才能做到这一点?

Use Series.map with replace non matched missing values by fillna :使用Series.map通过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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM