Search code examples
pythondataframedifference

Difference/subtraction of two DataFrames on numerical variables


I have a basic problem to do the difference of two dataframes on numeric columns. The rows are identical on other columns.

df1 :

     Name Sex    CA   PV  Time
0    John   M  5723  225    85
1  Andrew   M  6678  193    41
2  Gloria   F  8781  521    70
3    Paul   M  9910  502    31

df2 :

     Name Sex    CA   PV  Time
0    John   M  2082   35    60
1  Andrew   M  4567   60    18
2  Gloria   F  2676  486    52
3    Paul   M  9814  360    11

So, I would like to obtain the following DataFrame which is simply the difference on CA, PV and time df3 :

     Name Sex    CA   PV  Time
0    John   M  3641  190    25
1  Andrew   M  2111  133    23
2  Gloria   F  6105   35    18
3    Paul   M    96  142    20

If you have any idea to this simply ? Thanks


Solution

  • df1.update(df1.select_dtypes('number') - df2.select_dtypes('number'),overwrite=True)