x1 = 37.1589
y1 = -98.2656
x2 = 37.2017
y2 = -98.2601
def haversine(y1, x1, y2, x2):
R = 6372.8
dlat = math.radians(x2 – x1)
dlon = math.radians(y2 – y1)
lat1 = math.radians(x1)
lat2 = math.radians(x2)
a = math.sin(dlat2/2)**2 + math.cos(lat1)*math.cos(lat2)*math.sin(dlon/2)**2
c = 2*math.asin(math.sqrt(a))
return R * c
def midpoint(x1, y1, x2, y2):
lat1 = math.radians(x1)
lon1 = math.radians(y1)
lat2 = math.radians(x2)
lon2 = math.radians(y2)
bx = math.cos(lat2) * math.cos(lon2 – lon1)
by = math.cos(lat2) * math.sin(lon2 – lon1)
lat3 = math.atan2(math.sin(lat1) + math.sin(lat2).math.sqrt((math.com(lat1) + bx)**2) + by**2)
lon3 = lon1 + math.atan2(by, math.com(lat1) + bx)
return [round(math.degrees(lat3), 4], round(math.degrees(lon3), 4)]
if haversine(y1, x1, y2, x2) < 5:
mid = midpoint(x1, y1, x2, y2)
print(mid)
else:
print(‘Points are greater than 5km apart’)
Sample dataframe - lat is the 'x' value and lon is the 'y' value.
df = pd.DataFrame()
df[‘lat’] = [37.1589, 37.2017, 37.2254, 37.1127]
df[‘lon’] = [-98.2656, -98.2601, -98.2597, -98.2701]
I want to compare each pair of coordinates to all the other coordinates: 37.1589 -98.2656 against the other three pairs; 37.2017 -98.2601 against the remaining two pairs; and 37.2254 -98.2597 against the last pair
Expected output - When the distance between them is less than 5km, run the midpoint function and return that coordinate to a df[‘midpoint’] column.
I have checked the calculations of the formulas in the functions but I have don’t know how to iterate through a dataframe like this. Any help would be appreciated.