Search code examples
pythonpandasdataframesubtraction

Subtract two dataframes of different size, but maintain at least the size of the first dataframe


I have a DataFrame df and from there I want to subtract df2.

The caveat is that I want df to maintain the same size, and for every element in df, I want to minus df2 (if there is not such unique index/column in df2), it would just be df(i,j) - 0 (as no such index/column found in df2).

Example:

df:

Date    Blue    Dog Apple
1/1/2016    3   4   2
1/1/2015    3   4   2
1/1/2014    3   4   2
1/1/2013    3   4   2
1/1/2013    3   4   2
1/1/2013    3   4   2

df2:

Date    Apple   Blue    Cat
1/1/2017    1   3   2
1/1/2016    1   3   2
1/1/2015    1   3   2
1/1/2014    1   3   2

I want df - df2 to look like this:

Date    Blue    Dog Apple
1/1/2016    0   4   1
1/1/2015    0   4   1
1/1/2014    0   4   1
1/1/2013    3   4   2
1/1/2012    3   4   2
1/1/2011    3   4   2

Thank you.


Solution

  • Fill back the gaps:

    (df-df2).combine_first(df).reindex_like(df).astype(int)
    Out[45]: 
              Blue  Dog  Apple
    Date                      
    1/1/2016     0    4      1
    1/1/2015     0    4      1
    1/1/2014     0    4      1
    1/1/2013     3    4      2
    1/1/2012     3    4      2
    1/1/2011     3    4      2