I have a numpy array arr
and I want to create a new array with the n
elements of the old one, that are the closest to a given number x
. I've found a helpful answer here (I have need the N minimum (index) values in a numpy array), but my code seems very clumsy (I'm a beginner in Python):
def give_array_with_closest(x, n, arr):
newar = np.absolute(arr - (np.ones(len(arr)) * x)) #Subtract x from all array entries and take absolute value, so that the lowest entries are the ones closest to x
indexar = (newar).argsort()[:n] #get array with indices from n lowest entries of newar
result = np.empty(n)
for i in range(n):
result[i] = arr[indexar[i]]
return result
Since I'm not interested in the indices but only the actual entries, maybe the solution of the other question isn't the best in this case. Is there a more efficient and simpler way to do this?