仅当值存在时,才将列中的值替换为VLOOKUP另一个数据帧 [英] Replace a value in a column by vlookup another dataframe only if the value exists

查看:0
本文介绍了仅当值存在时,才将列中的值替换为VLOOKUP另一个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据(df2.Name1, df2.Name2)中的映射表覆盖我的df1.Name值。但是,并非df1.Name中的所有值都存在于df2.Name1

df1:

Name
Alex
Maria 
Marias
Pandas
Coala

df2:

Name1   Name2
Alex    Alexs
Marias  Maria
Coala   Coalas

预期结果:

Name
Alexs
Maria
Maria
Pandas
Coalas

我在网上尝试了几种解决方案,例如使用Map功能。通过在词典中翻转df2,我使用的是df1.Name = df1.Name.map(Dictionary),但这将导致nan中的所有值都不在df2中,如下所示。

Name
Alexs
Maria
Maria
NAN
Coalas
我不确定如何使用if语句来仅替换df2中确实存在的那些,并保留df1中的其余部分。 我还试图用if语句创建一个函数,但失败了。

如何处理此问题?

推荐答案

使用replace

df1.Name.replace(df2.set_index('Name1').Name2.to_dict())
Out[437]: 
0     Alexs
1     Maria
2     Maria
3    Pandas
4    Coalas
Name: Name, dtype: object

这篇关于仅当值存在时,才将列中的值替换为VLOOKUP另一个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆