Skip to content
Advertisement

Finding all the rows with the approximate values that match a condition in a dataframe

I have a panda’s dataframe that is something like this

JavaScript

The el1, el2, and el3 do not matter at all. I want to find the row with the X nearest to x=20

so I do

JavaScript

which gives me the index where x=19.3 is

So far so good

Now, the real problem

Imagine I have a dataframe where x goes from 6 to 31 and then again from 7 to 45 and then again from 2 to 27

I want a way to find a list of indexes [idx1, idx2...idxn] (in the above example n would be 3) with the most approximate values to say for example 20.

How can I do this with pandas and python?

EDIT: An example of the df would be

JavaScript

The rows I want are the ones where x=19.3 x=19.8 x=x=19.9

Advertisement

Answer

Assuming you have consecutive stretches of increasing values and want to find the closest to 20 for each:

JavaScript

example input:

JavaScript

output:

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