Skip to main content
 首页 » 编程设计

Python:如何将给定距离内的点组合在一起

2024年10月24日8dyllove98

我有一个数据框,其中包含用户在不同点(纬度/经度)之间的出发地和目的地行程。所以我们有 Origin_X, Origin_Y和 Destination_X, Destination_Y

df: 
 
Trip Origin_X  Origin_Y  Destination_X Destination_Y 
1   -33.55682 -70.78614   -33.44007     -70.6552 
2   -33.49097 -70.77741   -33.48908     -70.76263 
3   -33.37108 -70.6711    -33.73425     -70.76278 

我想将所有 Trip 组合在一起半径为 1km无论是在起点还是终点。如果出发地距离和目的地距离为 d<=1km,则可以将两个行程分组。 .为了计算两个坐标之间的距离,我使用了 haversine功能。

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))  
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles 
    return c * r 

请您参考如下方法:

这里是你如何做到的:

import pandas as pd 
from math import * 
 
def haversine(row): 
    """ 
    Calculate the great circle distance between two points  
    on the earth (specified in decimal degrees) 
    """ 
    # convert decimal degrees to radians  
    lon1 = row[1] 
    lat1 = row[2] 
    lon2 = row[3] 
    lat2 = row[4] 
    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))  
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles 
    return c * r 
 
#Copy the trip details provided by in this question 
 
df = pd.read_clipboard() 
df['dist'] = df.apply(haversine, axis=1) 
 
print df 
 
   Trip  Origin_X  Origin_Y  Destination_X  Destination_Y       dist 
0     1 -33.55682 -70.78614      -33.44007      -70.65520  15.177680 
1     2 -33.49097 -70.77741      -33.48908      -70.76263   1.644918 
2     3 -33.37108 -70.67110      -33.73425      -70.76278  16.785898 
#To group 
dfg = df.groupby(df['dist'] < 1) 
 
#Just to select all the trips that are less than 2 radius 
df[df['dist']<2] 
   Trip  Origin_X  Origin_Y  Destination_X  Destination_Y      dist 
1     2 -33.49097 -70.77741      -33.48908      -70.76263  1.644918