[英]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:我想,以取代
Status
在df1
与Status
在df2
如果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.