使用Haversine计算行之间的距离

问题描述

使用以下haversine公式以及两个不同的纬度和经度坐标,我可以检查这两个坐标是否彼此相距100米以内:

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,lat2 = map(radians,[lon1,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

radius = 0.1 # in kilometer

lon1 = train_data_sample["longitude"].loc[train_data_sample.index==0]
lat1 = train_data_sample["latitude"].loc[train_data_sample.index==0]

lon2 = train_data_sample["longitude"].loc[train_data_sample.index==1]
lat2 = train_data_sample["latitude"].loc[train_data_sample.index==1]

loc = haversine(lon1,lat2)

if loc <= radius:
    print('Inside the area')
else:
    print('Outside the area')

对于以下示例表,我想为每一行计算100米半径内的所有属性的中位数价格。

latitude    longitude   price
0   55.6632 12.6288 2595000
1   55.6637 12.6291 2850000
2   55.6637 12.6291 2850000
3   55.6632 12.6290 3198000
4   55.6632 12.6290 2995000
5   55.6638 12.6294 2395000
6   55.6637 12.6291 2995000
7   55.6642 12.6285 4495000
8   55.6632 12.6285 3998000
9   55.6638 12.6294 3975000

我的想法是,对于每一行,都要遍历所有坐标,对于100米半径内的所有行,请计算中位数价格,并使用中位数创建新列。

最终结果应该是这样:

latitude    longitude   price    median_price_radius_100
0   55.6632 12.6288 2595000      whatever the median price is
1   55.6637 12.6291 2850000
2   55.6637 12.6291 2850000
3   55.6632 12.6290 3198000
4   55.6632 12.6290 2995000
5   55.6638 12.6294 2395000
6   55.6637 12.6291 2995000
7   55.6642 12.6285 4495000
8   55.6632 12.6285 3998000
9   55.6638 12.6294 3975000

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)