Abhilash
Abhilash

Reputation: 2953

find nearest value above and below a value inside numpy array

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?

Upvotes: 0

Views: 733

Answers (1)

Reti43
Reti43

Reputation: 9797

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.

Upvotes: 2

Related Questions