'How to calculate furthest distance in similar group
Here's my data
Point Group Longitude Latitude
A 1 100 101
B 1 99 102
C 1 101 101
D 1 102 101
E 2 90 103
F 2 89 105
G 2 91 104
H 2 92 103
What I need is
Group distance Origin Destination
1 3.16227 B D
2 3.60555 F H
Notes: You can use Haversine distance for better approximation, I calculate dataframe above just using pythagorean theorem, below the Haversine equation
from sklearn.neighbors import BallTree, DistanceMetric
from math import radians, cos, sin, asin, sqrt
import pandas as pd
import numpy as np
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
# Radius of earth in kilometers is 6371
km = 6371* c
return km
Regards
Solution 1:[1]
You may can create you own function with scipy
from scipy.spatial.distance import cdist
def yourfunc(y) :
a = cdist(y[['Longitude', 'Latitude']], y[['Longitude', 'Latitude']], metric='euclidean')
a_max = a.max()
idx = np.where(a == a_max)[0]
return pd.Series([a_max]+y['Point'].iloc[idx].tolist(),index = ['distance','Origin','Destination'])
df.groupby('Group').apply(yourfunc)
Out[27]:
distance Origin Destination
Group
1 3.162278 B D
2 3.605551 F H
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BENY |
