代码之家  ›  专栏  ›  技术社区  ›  user2696565

使用另一个数据帧仅更新数据帧中的某些值

  •  0
  • user2696565  · 技术社区  · 4 年前

    如何用另一个数据帧中的值更新数据帧中一列中的某些值:

    # Main dataframe
    df1 = pd.DataFrame({'a':[1,2,3,4,5], 'b':['a2', 'a1', '?', '?', 'b2'], 'c':[100,101, 102, 103, 104]})
    
    # Dataframe with new values for column 'b'
    df2 = pd.DataFrame({'a':[3,4], 'b':['b5', 'c5']})
    
    # Result: Main dataframe with updated values for 'b', using column 'a' as index/key
    pd.DataFrame({'a':[1,2,3,4,5], 'b':['a2', 'a1', 'b5', 'c5', 'b2'], 'c':[100,101, 102, 103, 104]})
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   It_is_Chris    4 年前

    你可以替换 ? 具有 numpy.nan combine_first

    df1 = df1.replace('?', np.nan)
    df1.set_index('a').combine_first(df2.set_index('a')).reset_index()