Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting two dataframes by selecting only specific columns

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.

like image 489
André Luiz França Batista Avatar asked Nov 11 '19 12:11

André Luiz França Batista


1 Answers

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
like image 120
jezrael Avatar answered Sep 22 '22 11:09

jezrael