【问题标题】:How to replace the values in a dataframe column based on another dataframe condition如何根据另一个数据框条件替换数据框列中的值
【发布时间】:2019-01-31 03:48:49
【问题描述】:

我有两个数据框,XXX 和覆盖。

XXX = pd.DataFrame({'A':['One', 'Two', 'Three'], 'B': [6,4,3], 'C': ['red','green','blue']})

override = pd.DataFrame({'A':['One','Two'], 'C': ['apple','pie']})

我正在寻找替换XXX数据框C列值的最佳方法,其中覆盖数据框A列的值 等于数据框XXX的A列中的值。

我尝试使用 XXX ['C'] = XXX.merge(覆盖,on = "A")。 C_y 但“三”行的“蓝色”值被替换为 NaN 但 我想保留原来的“蓝色”值。

使用 A 字段作为键的最佳和最有效的方法是什么,即 XXX.A = override.A。 非常感谢

【问题讨论】:

    标签: python-3.x pandas dataframe replace


    【解决方案1】:

    您可以在系列映射器上使用 mapfillna

    In [1077]: XXX.A.map(override.set_index('A')['C']).fillna(XXX.C)
    Out[1077]:
    0    apple
    1      pie
    2     blue
    Name: A, dtype: object
    

    In [1078]: XXX.C = XXX.A.map(override.set_index('A')['C']).fillna(XXX.C)
    
    In [1079]: XXX
    Out[1079]:
           A  B      C
    0    One  6  apple
    1    Two  4    pie
    2  Three  3   blue
    

    【讨论】:

      【解决方案2】:

      使用update

      XXX=XXX.set_index('A')
      XXX.update(override.set_index('A'))
      XXX
      Out[471]: 
             B      C
      A              
      One    6  apple
      Two    4    pie
      Three  3   blue
      XXX.reset_index()
      Out[472]: 
             A  B      C
      0    One  6  apple
      1    Two  4    pie
      2  Three  3   blue
      

      【讨论】:

      • @Onyambu 这是基于一个假设。 index 是连接两个数据框的关键。
      猜你喜欢
      • 2021-09-08
      • 2022-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多