Pandas将一个数据帧覆盖在另一个数据帧上

时间:2018-03-09 21:30:56

标签: python pandas dataframe join merge

我有两个数据框,它们具有相同的列和完全相同的行数

数据帧1具有原始数据,数据帧2包含已更改的字段(更改的字段包含新值,未更改的字段为nan)。

我想基本上覆盖"新数据"在df 2中,在df 1中的数据上得到结果。

df1:

Key   a    b

123   6    1
124   7    6
125   3    5

df2:

Key   a    b

123   nan  nan
124   8    nan
125   nan  4

Result df:

Key   a    b

123   6    1
124   8    6
125   3    4

1 个答案:

答案 0 :(得分:5)

您需要combine_first

df2.combine_first(df1)

输出:

Key    a    b       
123  6.0  1.0
124  8.0  6.0
125  3.0  4.0