Overwrite columns in DataFrames of different sizes pandas

前端 未结 3 954
梦如初夏
梦如初夏 2021-01-13 13:20

I have following two Data Frames:

df1 = pd.DataFrame({\'ids\':[1,2,3,4,5],\'cost\':[0,0,1,1,0]})
df2 = pd.DataFrame({\'ids\':[1,5],\'cost\':[1,4]})
         


        
3条回答
  •  抹茶落季
    2021-01-13 14:05

    You can use set_index and combine first to give precedence to values in df2

    df_result = df2.set_index('ids').combine_first(df1.set_index('ids'))
    df_result.reset_index()
    

    You get

       ids  cost
    0   1   1
    1   2   0
    2   3   1
    3   4   1
    4   5   4
    

提交回复
热议问题