首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >距离矩阵Haversine

距离矩阵Haversine
EN

Stack Overflow用户
提问于 2022-04-01 07:24:31
回答 1查看 254关注 0票数 -1

我正在开发一个如下所示的数据框架:

代码语言:javascript
复制
             lat       lon
id_zone
0        40.0795  4.338600
1        45.9990  4.829600
2        45.2729  2.882000
3        45.7336  4.850478
4        45.6981  5.043200

我在试着做一个Haverisne距离矩阵。基本上,对于每个区域,我想计算它和数据中所有其他区域之间的距离。所以对角线上应该只有0。这是我使用的Haversine函数,但是我不能建立我的矩阵。

代码语言:javascript
复制
def haversine(x):
    x.lon, x.lat, x.lon2, x.lat2 = map(radians, [x.lon, x.lat, x.lon2, x.lat2])
    # formule de Haversine
    dlon = x.lon2 - x.lon
    dlat = x.lat2 - x.lat
    a = sin(dlat / 2) ** 2 + cos(x.lat) * cos(x.lat2) * sin(dlon / 2) ** 2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    km = 6367 * c
    return km
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-01 08:52:24

您可以使用这个答案的解决方案Pandas - Creating Difference Matrix from Data Frame

或者在您的具体案例中,您有一个类似于本例的DataFrame:

代码语言:javascript
复制
             lat       lon
id_zone
0        40.0795  4.338600
1        45.9990  4.829600
2        45.2729  2.882000
3        45.7336  4.850478
4        45.6981  5.043200

您的功能被定义为:

代码语言:javascript
复制
def haversine(first, second):
    # convert decimal degrees to radians
    lat, lon, lat2, lon2 = map(np.radians, [first[0], first[1], second[0], second[1]])

    # haversine formula
    dlon = lon2 - lon
    dlat = lat2 - lat
    a = np.sin(dlat/2)**2 + np.cos(lat) * np.cos(lat2) * np.sin(dlon/2)**2
    c = 2 * np.arcsin(np.sqrt(a))
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles
    return c * r

其中传递latlonfirst位置和second位置。

然后,您可以使用Numpy创建一个距离矩阵,然后用haversine函数的距离结果替换零:

代码语言:javascript
复制
# create a matrix for the distances between each pair of zones
distances = np.zeros((len(df), len(df)))
for i in range(len(df)):
    for j in range(len(df)):
        distances[i, j] = haversine(df.iloc[i], df.iloc[j])
pd.DataFrame(distances, index=df.index, columns=df.index)

您的输出应该类似于以下内容:

代码语言:javascript
复制
id_zone           0           1           2           3           4
id_zone
0          0.000000  659.422944  589.599339  630.083979  627.383858
1        659.422944    0.000000  171.597296   29.555376   37.325316
2        589.599339  171.597296    0.000000  161.731366  174.983855
3        630.083979   29.555376  161.731366    0.000000   15.474533
4        627.383858   37.325316  174.983855   15.474533    0.000000
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71703229

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档