Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas overlay one dataframe on another

I have two data frames which have identical columns and the exact same number of rows

Data frame 1 has the original data and data frame 2 contains the fields which have changed (changed fields contain the new value, unchanged fields are nan).

I want to essentially overlay the "new data" in df 2 over the data in df 1 and get the result below.

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
like image 809
Mustard Tiger Avatar asked Jan 29 '23 13:01

Mustard Tiger


1 Answers

You need combine_first:

df2.combine_first(df1)

Output:

Key    a    b       
123  6.0  1.0
124  8.0  6.0
125  3.0  4.0
like image 128
Scott Boston Avatar answered Jan 31 '23 07:01

Scott Boston