Note that it took some time to retrieve the value closest to a certain value from the list in Python.
I saw how to use numpy's searchsorted function on the net, but this function inserts a value into the list Since it is a function that returns the index when doing so, it does not always return the index of the value closest to a certain value.
** Example of actual failure **
Failure example.py
# coding: utf-8
import numpy as np
def getNearestValue(list, num):
#Get index when inserting in ascending order
sortIdx = np.searchsorted(list, num, side='left')
return list[sortIdx]
if __name__ == "__main__":
list = [0, 0.5, 1]
print(getNearestValue(list, 0.1)) # →0 OK
print(getNearestValue(list, 0.4)) # →0 NG
The closest value to 0.4
in the list element of the above code is 0.5, but 0 is returned.
~~ Therefore, we implemented a function that calculates the difference between the target values from the peripheral elements of the index obtained by the searchsorted function and extracts the value closest to a certain value. ~~
** Addendum: 2016/08/24 ** kochory gave me a code that has been greatly streamlined. It is implemented by calculating the difference between a certain value and the elements in the list and finding the index of the minimum value. Thank you!
getNearestValue_sample2.py
# coding: utf-8
import numpy as np
def getNearestValue(list, num):
"""
Overview:A function that returns the value closest to a value from the list
@param list:Data array
@param num:Target value
@return The value closest to the target value
"""
#Calculate the difference between the list element and the target value and get the index of the minimum value
idx = np.abs(np.asarray(list) - num).argmin()
return list[idx]
if __name__ == "__main__":
list = [0, 0.5, 1]
print(getNearestValue(list, -0.1)) # →0
print(getNearestValue(list, 0.1)) # →0
print(getNearestValue(list, 0.4)) # →0.5
print(getNearestValue(list, 0.5)) # →0.5
print(getNearestValue(list, 0.6)) # →0.5
print(getNearestValue(list, 0.8)) # →1
print(getNearestValue(list, 1.2)) # →1
Recommended Posts