【问题标题】:Pandas: Replace values within particular column of one dataframe based on a column in other dataframe熊猫:根据其他数据框中的一列替换一个数据框的特定列中的值
【发布时间】:2017-10-08 09:05:55
【问题描述】:

我正在尝试比较“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

【问题讨论】:

  • 这项工作可以吗:df1.loc[~df1['Names'].isin(df2['Names']), 'Names'] = 'Other'
  • 它有效..你太棒了!
  • @stephan,您介意将您的评论变成答案吗?这样问题就不会一直悬而未决?
  • @MaxU:根据您的要求完成。只是不确定我是否完全理解了这个问题。

标签: python pandas dataframe ipython


【解决方案1】:

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

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

然后您可以使用结果来select 要更改的值,并通过赋值来更改这些值:

df1.loc[~df1['Names'].isin(df2['Names']), 'Names'] = 'Other'

【讨论】:

    【解决方案2】:
    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's method 更惯用,而且很可能也会更快

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      相关资源
      最近更新 更多