Python – Find all indexes of the numpy array closest to the value

Find all indexes of the numpy array closest to the value… here is a solution to the problem.

Find all indexes of the numpy array closest to the value

In a numpy array, the indices of all values closest to a given constant are required.
The background is digital signal processing. The array contains the amplitude function of the filter (np.abs(np.fft.rfft(h)) and has an amplitude of, for example, 0.5 or, in another case, 0.
Most of the time, the values in question are not fully included in the sequence. The index of the closed value should be found here.

So far, I came up with the following method to see the sign change of the difference between sequence and constant. However, this applies only to monotonically increasing or decreasing sequences at the relevant point. Sometimes it also turns off 1.

def findvalue(seq, value):
    diffseq = seq - value
    signseq = np.sign(diffseq)
    signseq[signseq == 0] = 1
    return np.where(np.diff(signseq))[0]

I wonder if there is a better solution. It only works with one-dimensional true float groups, which in my case are not very demanding on computational efficiency.

As a numeric example, the following code should return [8, 41]. For simplicity, I have replaced the filter amplitude response with a half-wave here.

f=np.sin(np.linspace(0, np.pi))
findvalue(f, 0.5)

Similar issues I found are as follows, but they only return the first or second index:
Find the second closest index to value

Find nearest value in numpy array

Solution

The following function returns a decimal index showing approximately when the value is exceeded:

def FindValueIndex(seq, val):
    r = np.where(np.diff(np.sign(seq - val)) != 0)
    idx = r + (val - seq[r]) / (seq[r + np.ones_like(r)] - seq[r])
    idx = np.append(idx, np.where(seq == val))
    idx = np.sort(idx)
    return idx

Logic: Find where the symbol for seq – val changes. Take the values below and above the transition and interpolate the values. is added to the index, where the value is actually equal to the value.

If you want an integer index, just use np.round. You can also choose np.floor or np.ceil to round the index to your liking.

def FindValueIndex(seq, val):
    r = np.where(np.diff(np.sign(seq - val)) != 0)
    idx = r + (val - seq[r]) / (seq[r + np.ones_like(r)] - seq[r])
    idx = np.append(idx, np.where(seq == val))
    idx = np.sort(idx)
    return np.round(idx)

Related Problems and Solutions