1
votes

I have the following problem: I have two pandas data frames of different length containing some rows that have common values and some that are different like this:

df1

     s1  s2  s3  s4
sp1   1   0   1   1
sp2   1   1   0   1
sp3   1   1   1   0
sp4   1   1   1   1

df2

     s1  s2  s3  s4
sp1   1   0   1   1
sp3   1   1   1   0
sp5   1   1   1   1

I would like to merge the two tables with the following result:

     s1  s2  s3  s4
sp1   2   0   2   2
sp2   1   1   0   1
sp3   2   2   2   0
sp4   1   1   1   1
sp5   1   1   1   1

Is that possible to merge the two dataframe and make the addition of the common cells?

1
You could do (df1 + df2).fillna(df1).fillna(df2) - EdChum

1 Answers

4
votes

Solution

df1.add(df2, fill_value=0)

or

df1.add(df2, fill_value=0).astype(int)

This does exactly what you want using arguments intended to solve this exact problem. I added astype(int) at the end to preserve int