Find nearest value in numpy array

后端 未结 16 1990
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 10:18

Is there a numpy-thonic way, e.g. function, to find the nearest value in an array?

Example:

np.find_nearest( array, value )
16条回答
  •  醉话见心
    2020-11-22 10:39

    For large arrays, the (excellent) answer given by @Demitri is far faster than the answer currently marked as best. I've adapted his exact algorithm in the following two ways:

    1. The function below works whether or not the input array is sorted.

    2. The function below returns the index of the input array corresponding to the closest value, which is somewhat more general.

    Note that the function below also handles a specific edge case that would lead to a bug in the original function written by @Demitri. Otherwise, my algorithm is identical to his.

    def find_idx_nearest_val(array, value):
        idx_sorted = np.argsort(array)
        sorted_array = np.array(array[idx_sorted])
        idx = np.searchsorted(sorted_array, value, side="left")
        if idx >= len(array):
            idx_nearest = idx_sorted[len(array)-1]
        elif idx == 0:
            idx_nearest = idx_sorted[0]
        else:
            if abs(value - sorted_array[idx-1]) < abs(value - sorted_array[idx]):
                idx_nearest = idx_sorted[idx-1]
            else:
                idx_nearest = idx_sorted[idx]
        return idx_nearest
    

提交回复
热议问题