繁体   English   中英

熊猫:根据其他数据框中的列替换一个数据框中的特定列中的值

[英]Pandas: Replace values within particular column of one dataframe based on a column in other dataframe

我正在尝试比较“ df2”数据框“名称”列中的值是否存在于“ df1”的“名称”列中。 我想用自定义字符串'Other'更新df1 ['Names']中的不匹配值。 我不想编辑其他列中的任何值。

有人可以帮我获得预期的结果吗?

df1
    Names     Method
0   Ram       GET
1   Sham      POST
2   Ganesh    READ
3   Ramesh    GET
4   Deepak    POST

df2
    Names
0   Sham
1   Ram

df1的预期结果:

df1
    Names     Method
0   Ram       GET
1   Sham      POST
2   Other     READ
3   Other     GET
4   Other     POST

您可以使用isin来检查一个序列或框架的值是否在另一个序列中。 要获得“ not in”,只需用~取反结果:

>>> ~df1['Names'].isin(df2['Names'])
0     False
1     False
2     True
3     True
4     True

然后,您可以使用结果来选择要更改的值,并通过赋值来更改它们:

df1.loc[~df1['Names'].isin(df2['Names']), 'Names'] = 'Other'
In [39]: df1.loc[df1.query("Names not in @df2.Names").index, 'Names'] = 'Other'

In [40]: df1
Out[40]:
   Names Method
0    Ram    GET
1   Sham   POST
2  Other   READ
3  Other    GET
4  Other   POST

注意: @stephan的方法更惯用,而且很有可能也会更快

暂无
暂无

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

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