简体   繁体   English

Python:减去两个数据帧

[英]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我想从 df1 中减去 df2 得到以下结果

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.但是, df1.subtract(df2)会为不在 df1 中的索引生成空单元格。 Is there another to do this, preserving all other indexes in df2?是否有另一个这样做,保留 df2 中的所有其他索引?

EDIT: Fixed values in df编辑: df中的固定值

You need to add a fill_value :您需要添加一个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的索引:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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