简体   繁体   中英

Subtract DataFrames with Different Columns

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?

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

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