Sorting a 2D numpy array on to the proximity of each element to a certain point
Sorting to find the nearest point is not a good idea. If you want the closest point then just find the closest point instead, sorting for that is overkilling.
def closest_point(arr, x, y):
dist = (arr[:, 0] - x)**2 + (arr[:, 1] - y)**2
return arr[dist.argmin()]
Moreover if you need to repeat the search many times with a fixed or quasi fixed set of points there are specific data structures that can speed up this kind of query a lot (the search time becomes sub-linear).
If you just want the cartesian distance you can do something like the following:
def find_nearest(arr,value):
newList = arr - value
sort = np.sum(np.power(newList, 2), axis=1)
return newList[sort.argmin()]
I am assuming newList
has a shape of (n,2). As a note I changed the input variable array
to arr
to avoid issues if numpy is imported like: from numpy import *
.