Reputation: 5278
I have a DataFrame df1
with Columns A
, B
and D
.
| A | B | D |
-------------
| 1 | 5 | 3 |
| 2 | 3 | 1 |
and a DataFrame df2
with Columns B
and C
.
| B | C |
---------
| 0 | 2 |
| 3 | 5 |
They have the same number of rows.
I want to subtract them cellwise (df1 - df2
). But each of them has columns that the other doesn't have.
The resulting DataFrame I'm aiming for looks like this:
| A | B | C | D |
------------------
| 1 | 5 | -2 | 3 |
| 2 | 0 | -5 | 1 |
Is this easily possible?
Upvotes: 0
Views: 1071
Reputation: 215137
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):
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:
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
Upvotes: 3