Subtract two DataFrames with non-overlapping indexes

I am trying to subtract two DataFrames together. I would like to treat the missing values โ€‹โ€‹as 0. fillna() will not work here because I do not know the general indexes before doing the subtraction:

 import pandas as pd A = pd.DataFrame([1,2], index=['a','b']) B = pd.DataFrame([3,4], index=['a','c']) A - B 0 a -2 b NaN c NaN 

Ideally, I would like to:

 A - B 0 a -2 b 2 c -4 

Is this possible while keeping the code simple?

+5
source share
1 answer

You can use the subtract method and specify a fill_value zero:

 A.subtract(B, fill_value=0) 

Note: the method below, combineAdd , is deprecated from 0.17.0 onwards.

One way is to use the combineAdd method to add -B to A :

 >>> A.combineAdd(-B) 0 a -2 b 2 c -4 

Using this method, two DataFrames are added, and the values โ€‹โ€‹in non-matching indexes default to the value in A or B

+5
source

Source: https://habr.com/ru/post/1213006/


All Articles