Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge dataframes on the next highest key value

I have df1:

a
2013
2014
2015

and df2

a
2014
2017
2018
2021

My goal would be that the key a from df1 merges onto the next highest key in df2 e.g. 2013->2014, 2014->2017 and 2015->2017. So even if both keys are equal I’d like to merge on the next highest, would that be possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use merge_asof with direction='forward' and parameter allow_exact_matches=False:

df = pd.merge_asof(df1, df2.rename(columns={'a':'a1'}),
                   left_on='a', 
                   right_on='a1',
                   direction='forward',
                   allow_exact_matches=False)
print (df)
      a    a1
0  2013  2014
1  2014  2017
2  2015  2017
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading