Skip to content
Advertisement

Find value smaller but closest to current value

I have a very large pandas dataframe that contains two columns, column A and column B. For each value in column A, I would like to find the largest value in column B that is less than the corresponding value in column A. Note that each value in column B can be mapped to many values in column A.

Here’s an example with a smaller dataset. Let’s say I have the following dataframe:

JavaScript

I would like to find some third column — say c — so that

c = [nil, 2, 5, 1, 2, 2].

Note that each entry in c is strictly less than the corresponding value in c.

Upon researching, I think that I want something similar to pandas.merge_asof, but I can’t quite get the query correct. In particular, I’m struggling because I only have one dataframe and not two. Perhaps I can form a second dataframe from my current one to get what I need, but I can’t quite get it right. Any help is appreciated.

Advertisement

Answer

Yes, it is doable using pandas.merge_asof. Explanation as comments in the code –

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