I have two dataframes df1
and df2
like this:
round fouls goals team_id
0 1 15 1 262
1 1 10 2 263
2 1 5 0 315
3 1 7 3 316
round fouls goals team_id
0 2 23 3 262
1 2 13 5 263
2 2 11 3 315
3 2 19 5 316
What I want to do is perform a subtraction like df3 = df2 - df1
. However I would like to subtract only the fouls
and goals
columns and keep the round
and team_id
columns unchanged.
If I perform df3 = df2 - df1
I get:
round fouls goals team_id
0 1 8 2 0
1 1 3 3 0
2 1 6 3 0
3 1 12 2 0
What can I do in order to get the following:
round fouls goals team_id
0 2 8 2 262
1 2 3 3 263
2 2 6 3 315
3 2 12 2 316
Thanks in advance.
You can specify columns for subtract in list:
cols = ['fouls','goals']
df2[cols] = df2[cols]- df1[cols]
print (df2)
round fouls goals team_id
0 2 8 2 262
1 2 3 3 263
2 2 6 3 315
3 2 12 2 316
Or specify columns for exclude columns names with Index.difference
for columns for subtract:
exclude = ['round','team_id']
cols = df1.columns.difference(exclude)
df2[cols] = df2[cols]- df1[cols]
print (df2)
round fouls goals team_id
0 2 8 2 262
1 2 3 3 263
2 2 6 3 315
3 2 12 2 316
For new DataFrame use:
df3 = df2.copy()
cols = df1.columns.difference(['round','team_id'])
df3[cols] = df2[cols]- df1[cols]
print (df3)
round fouls goals team_id
0 2 8 2 262
1 2 3 3 263
2 2 6 3 315
3 2 12 2 316
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With