Quickly Find the Index in an Array Closest to Some Value

后端 未结 3 1530
日久生厌
日久生厌 2020-12-18 01:34

I have an array of values, t, that is always in increasing order (but not always uniformly spaced). I have another single value, x. I need to find the index in t such that

3条回答
  •  忘掉有多难
    2020-12-18 01:44

    Use searchsorted:

    t = np.arange(10,100000)         # Not always uniform, but in increasing order
    x = np.random.uniform(10,100000)
    
    print t.searchsorted(x)
    

    Edit:

    Ah yes, I see that's what you do in f1. Maybe f3 below is easier to read than f1.

    def f3(t, x):
        ind = t.searchsorted(x)
        if ind == len(t):
            return ind - 1 # x > max(t)
        elif ind == 0:
            return 0
        before = ind-1
        if x-t[before] < t[ind]-x:
            ind -= 1
        return ind
    

提交回复
热议问题