How To Find The Closest Coordinate From A List Of Points?
Suppose I have a list of x, y coordinates as below: A = [(26, 63), (23, 63), (22, 63), (21, 63), (20, 63), (22, 62), (27, 63)] and I have a x, y coordinate of a point as below: l
Solution 1:
Numpy has a useful function : norm.
import numpy as np
A = [(26, 63), (25, 63), (24, 63), (23, 63), (22, 63), (21, 63), (20, 63), (22, 62), (27, 63)]
A = np.array(A)
leftbottom = np.array((0,238))
distances = np.linalg.norm(A-leftbottom, axis=1)
min_index = np.argmin(distances)
print(f"the closest point is {A[min_index]}, at a distance of {distances[min_index]}")
Result:
the closest point is [20 63], at a distance of 176.13914953808538
Solution 2:
You could use numpy
:
import numpy as np
A = [(26, 63), (25, 63), (24, 63), (23, 63), (22, 63), (21, 63), (20, 63), (22, 62), (27, 63)]
p = (0, 238)
xy = np.array(A).T
# euclidean distance
d = ( (xy[0] - p[0]) ** 2 + (xy[1] - p[1]) ** 2) ** 0.5
closest_idx = np.argmin(d)
closest = A[closest_idx]
print(closest)
(20, 63)
Solution 3:
You can get the closest coordinate simply in python.
Assume that leftbottom has same format with A.
leftbottom = [(x,y)]
import numpy as np
diffs = np.abs(np.array(A)-np.array(leftbottom))
dists = np.sum(dists,axis=1) #l1-distance
closest_point_index = np.argmin(dists)
Solution 4:
If you are looking for a solution without using numpy maybe this can help you
from math import sqrt
defmin_distance(x, y, iterable):
list_of_distances = list(map(lambda t: sqrt(pow(t[0]-x,2)+pow(t[1]-y,2)),iterable))
min_res = min(list_of_distances)
index_of_min = list_of_distances.index(min_res)
return iterable[index_of_min]
A = [(26, 63), (25, 63), (24, 63), (23, 63), (22, 63),(21, 63), (20, 63), (22, 62), (27, 63)]
a = min_distance(0, 238, A)
print(a)
Solution 5:
Here is a built-in solution, using the min()
function over the list of points with the key
argument being the distance of each point to the target
point, calculated with math.hypot
:
import math
points = [(26, 80), (23, 24), (22, 63), (2, 63)]
target = (1, 63)
print(min(points, key=lambda point: math.hypot(target[1]-point[1], target[0]-point[0])))
In this example, (2, 63)
will be printed.
Post a Comment for "How To Find The Closest Coordinate From A List Of Points?"