0

I have a key_value object that looks like this

v1          242.466667
v2          242.883333
v3          242.05
v4          245.183333
v5          247.066667

Name: acolumnname, dtype: object

What I want is find nearest value to the top & bottom along with the key I somehow managed to find the nearest value successfully like this

def find_nearest_key_value(key_value_object, base_value):
    values_array = np.asarray(key_value_object)
    idx = (np.abs(values_array - base_value)).argmin() #finds the closest
    key=key_value_object.keys()[idx] # finds the key for the value
    return key,value_array[idx]

Above works fine. But I want to find the nearest value above and below base_value aswell in 2 seperate methods

def find_nearest_higher_key_value(key_value_object, base_value):
     #returns nearest higher value with key

def find_nearest_lower_key_value(key_value_object, base_value):
    #returns nearest lower value with key

Could someone tell me how to do this?

1 Answer 1

2

For the nearest higher value, the difference of values_array - base_value will be positive when the value of your array is higher than base_value. Set all negative differences to infinity and then find the index of the lowest value.

def find_nearest_higher_key_value(key_value_object, base_value):
    values_array = np.asarray(key_value_object)
    diff = values_array - base_value
    diff[diff < 0] = np.inf
    idx = diff.argmin()
    key = key_value_object.keys()[idx]
    return key, value_array[idx]

For the lower value just switch the difference to base_value - values_array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.