Skip to content
Advertisement

Two DataFrames, find index of second one where values of two columns match up from first

I have two pandas DataFrames as pictured.

DF1:

JavaScript

DF2 (192 x 7):

JavaScript

I want to find the index value of DF2 where df1[0] & df1[1] match df2[0] & df2[2]. For more detail, this would be represented above as starting at index 3188 of DF2. DF1 values will be dynamically changing as DF2 stays constant.

Edit: Just noticed that there was an error in my logic. I meant DF1[0] == DF2[0] and DF1[1]==DF2[2]. I have updated above accordingly.

Advertisement

Answer

You can find the first place where DF2 matches DF1 with offset = DF2.loc[ (DF2[0] == DF1.loc[0,0]) & (DF2[1] == DF1.loc[0,1])] ][0]. If you want to then test whether the rest of the columns match up, you’ll have to get them to have the same shape and the same index. In this case, the part of DF2 after the matching row is smaller than DF1 overall, so one way to do this is as follows (if DF1 were smaller, the process would be a bit different):

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement