Skip to content
Advertisement

Pandas: Merge Dataframes Based on Condition but Keep NaN

I have two dataframes, df1 and df2, which I would like to merge on the column ‘id’ where the ‘triggerdate’ from df1 falls between the ‘startdate’ and ‘enddate’ of df2, however, keep the rows where there’s no match.

df1:

JavaScript

df2:

JavaScript

Expected Output:

JavaScript

The approach that I have taken so far is:

JavaScript

However, this approach does the following 1) Matches the ‘id’ values in df1 with df2 regardless of whether the condition is met and 2) then drops all the rows where the condition isn’t met.

Unfortunately, I had no luck finding the solution online.

What would be the recommended approach to get the expected output?

Thank you in advance for your help!

Advertisement

Answer

Try pd.merge_asof()

modify df2 to merge on date column

JavaScript

Then merge

JavaScript

Output:

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