Home > Back-end >  Python Pandas: Get the two largest values from a set of numbers but ensure they are x amount of valu
Python Pandas: Get the two largest values from a set of numbers but ensure they are x amount of valu

Time:11-17

Is it possible to use .nlargest to get the two highest numbers in a set of number, but ensure that they are x amount of rows apart?

For examples, in the following code I would want to find the largest values but ensure that they are more than 5 values apart from each other. Is there an easy way to do this?

   data = {'Pressure' : [100,112,114,120,123,420,1222,132,123,333,123,1230,132,1,23,13,13,13,123,13,123,3,222,2303,1233,1233,1,1,30,20,40,401,10,40,12,122,1,12,333],
       }

CodePudding user response:

If I understand the question correctly, you need to output the largest value, and then the next largest value that's at least X rows apart from it (based on the index).

First value is just data.Pressure.max(). Its index is data.Pressure.idxmax()

Second value is either before or after the first value's index:

max_before = df.Pressure.loc[:df.Pressure.idxmax() - X].max()
max_after = df.Pressure.loc[df.Pressure.idxmax()   X:].max()

second_value = max(max_before, max_after)
  • Related