Reputation: 21
Need to get a distances for lat long pairs using haversine distance for this data frame ( named df). The requirement is to get the distance added in a new column in the same data frame (df).
Name | geo1 | geo2 |
---|---|---|
ABC | (52.2296756,21.0122287) | (51.3490756,23.0922287) |
XYZ | (52.3490756,23.0922287) | (51.2296756,21.0122287) |
Upvotes: 0
Views: 311
Reputation: 21
This worked as well
#splitting lat longs
split_data = df.geo1.strip(')').str.strip('(').str.split(',')
df['geo1_lat'] = split_data.apply(lambda x: x[0])
df['geo1_long'] = split_data.apply(lambda x: x[1])
split_data = df.geo2.strip(')').str.strip('(').str.split(',')
df['geo2_lat'] = split_data.apply(lambda x: x[0])
df['geo2_long'] = split_data.apply(lambda x: x[1])
def haversine_distance(lat1, lon1, lat2, lon2):
r = 6371
phi1 = np.radians(lat1)
phi2 = np.radians(lat2)
delta_phi = np.radians(lat2 - lat1)
delta_lambda = np.radians(lon2 - lon1)
a = np.sin(delta_phi / 2)**2 + np.cos(phi1) * np.cos(phi2) * np.sin(delta_lambda / 2)**2
res = r * (2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)))
return np.round(res*1000, 2)
df['distance'] = df[['geo1_lat','geo1_long','geo2_lat','geo2_long']].apply(lambda x: haversine(x[1], x[0], x[3], x[2]), axis=1)
Upvotes: 0
Reputation: 120391
If you refer to this Python's implementation of haversine
distance:
df["distance"] = df[["geo1", "geo2"]].apply(lambda x: haversine(*x.geo1, *x.geo2), axis="columns")
>>> df
Name geo1 geo2 distance
0 ABC (52.2296756, 21.0122287) (51.3490756, 23.0922287) 248.451222
1 XYZ (52.3490756, 23.0922287) (51.2296756, 21.0122287) 258.456800
Upvotes: 1