Home > Mobile >  Python: Subtract two DataFrames
Python: Subtract two DataFrames

Time:07-16

I have two DataFrames:

df1:
            A    B    C 
Date
2022-01-01  0    100  0
2022-01-04  50   0    0
2022-02-08  0    0    200

df2:
            A    B    C 
Date
2022-01-01  0    200  0
2022-01-02  0    200  0
2022-02-03  0    200  0
2022-01-04  50   200  0
2022-01-05  100  200  0
2022-02-06  100  200  0
2022-01-07  100  200  0
2022-01-08  100  200  100
2022-02-09  100  200  300 

I want to subtract df2 from df1 to get the following

df:
            A    B    C 
Date
2022-01-01  0    100  0
2022-01-02  0    200  0
2022-02-03  0    200  0
2022-01-04  50   200  0
2022-01-05  100  200  0
2022-02-06  100  200  0
2022-01-07  100  200  0
2022-01-08  100  200  100
2022-02-09  100  200  300 

However, df1.subtract(df2) results in empty cells for the indexes that are not in df1. Is there another to do this, preserving all other indexes in df2?

EDIT: Fixed values in df

CodePudding user response:

You need to add a fill_value:

df1.subtract(df2, fill_value=0)

However, given the provided output, it looks more like you want an addition and to restrict the index to that of df2:

df2.add(df1.reindex_like(df2), fill_value=0)

output:

                A      B      C
Date                           
2022-01-01    0.0  300.0    0.0
2022-01-02    0.0  200.0    0.0
2022-02-03    0.0  200.0    0.0
2022-01-04  100.0  200.0    0.0
2022-01-05  100.0  200.0    0.0
2022-02-06  100.0  200.0    0.0
2022-01-07  100.0  200.0    0.0
2022-01-08  100.0  200.0  100.0
2022-02-09  100.0  200.0  300.0
  • Related