Calculate the subtraction of two columns in two dataframes by replacement

LamaMo :

I have df1 which contains:

IDs    values
E21    32
DD12   82
K99    222

And df2 that contains:

IDs   values
GU1   87
K99   93
E21   48

What I need is to check if the ID in df2 exists in df1, do the subtraction of the value of df1 - df2 for that ID and update the value in df2.

If the ID of df2 does not exist in df1, the value for that ID in df2 remains the same.

So, the result from the above example (basically df2 will be updated):

IDs    values
GU1    87 #the same not changed since it not exist in df1
K99    129 #exist in df1, do the subtraction 222-93=129
E21    -16 #exist in df1, do the subtraction 32-48=129

Any help, please?

Mykola Zotko :

You can use the method update:

df2.update(df1 - df2)

Output:

     values
IDs        
GU1    87.0
K99   129.0
E21   -16.0

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=8083&siteId=1