简体   繁体   中英

Python: Subtract two DataFrames

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM