Check two different dataframes with different number of rows and then apply operation

Viewed 41

I have two dataframes df1 and df2 with different total number of rows. I need to check which elements of the first column of df1 exist in the first column of df2. When there is a match, then I need to perform an operation between column 2 of df1 and df2. Example:

DF1      

col1   col2   
name1  value1 
name2  value2 
...    ...
nameN  valueN   

DF2
col1   col2   
name1  value1 
name2  value2 
...    ...
nameM  valueM 

If DF1[nameX] == DF2[nameY] then my_value = DF1[valueX] - DF2[valueY]. I managed to understand how to check whether the nameX and nameY are the same (I used isin()) but then I have problems understanding how to tell to calculate my_value iteratively if the condition is true.

2 Answers

You may try that:

for el1, el2 in zip(df1["col1"], df2["col1"]):
  if el1 == el2: 
    my_value = el1-el2
    print(my_value)

Get the match for 1st two column

match = df1.isin(df2)['col1']
match = match[match == True].index

do the operation according to match

df1.loc[match]['col2'] - df2.loc[match]['col2']
Related