简体   繁体   English

减去具有不同列的数据框

[英]Subtract DataFrames with Different Columns

I have a DataFrame df1 with Columns A , B and D . 我有一个带有ABD列的DataFrame df1

| A | B | D |
-------------
| 1 | 5 | 3 |
| 2 | 3 | 1 |

and a DataFrame df2 with Columns B and C . 以及带有BC列的DataFrame df2

| B | C |
---------
| 0 | 2 |
| 3 | 5 |

They have the same number of rows. 它们具有相同的行数。

I want to subtract them cellwise ( df1 - df2 ). 我想将它们逐个减去( df1 - df2 )。 But each of them has columns that the other doesn't have. 但是他们每个人都有其他人没有的列。

The resulting DataFrame I'm aiming for looks like this: 我针对的结果DataFrame看起来像这样:

| A | B |  C | D |
------------------
| 1 | 5 | -2 | 3 |
| 2 | 0 | -5 | 1 |

Is this easily possible? 这容易吗?

You can align the column index of the two data frames first, fill missing values with zero and then do the subtraction (assume the two data frames have the same row index): 您可以首先align两个数据框的列索引,用零填充缺失值,然后进行减法(假设两个数据框具有相同的行索引):

df1, df2 = df1.align(df2, fill_value=0)    
df1 - df2
#   A   B    C  D
#0  1   5   -2  3
#1  2   0   -5  1

Or use combine method: 或使用combine方法:

df1.combine(df2, pd.Series.sub, fill_value=0)
#   A   B      C    D
#0  1   5   -2.0    3
#1  2   0   -5.0    1

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

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