代码之家  ›  专栏  ›  技术社区  ›  Preetesh Gaitonde

Pandas:基于其他数据帧中的列替换一个数据帧的特定列中的值

  •  2
  • Preetesh Gaitonde  · 技术社区  · 7 年前

    有人能帮我得到预期的结果吗?

    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
        Names     Method
    0   Ram       GET
    1   Sham      POST
    2   Other     READ
    3   Other     GET
    4   Other     POST
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   stephan    7 年前

    isin 检查一个序列或帧的值是否在另一个序列或帧中。要得到“not is in”,只需用 ~ :

    >>> ~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
  •  1
  •   MaxU - stand with Ukraine    7 年前
    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 更地道,而且可能更快