[英]How to create distance table using geodesic
I'm calculating with Python.我正在用 Python 计算。 Let's say i have this kind of DataFrame where it consists of long lat of some points假设我有这种 DataFrame 它由一些点的长纬度组成
import pandas as pd
dfa=pd.DataFrame(([1,2],[1,3],[1,1],[1,4]), columns=['y','x'])
before, i used distance matrix from scipy.spatial and create another DataFrame with this code.之前,我使用来自 scipy.spatial 的距离矩阵并使用此代码创建另一个 DataFrame。 but it seems that it can't precisely calculate the distance between points (with long lat)但它似乎无法精确计算点之间的距离(长纬度)
from scipy.spatial import distance_matrix
pd.DataFrame(distance_matrix(dfa.values, dfa.values), index=dfa.index, columns=dfa.index)
Do you think it's possible to change the calculation with geodesic?你认为有可能用测地线改变计算吗? here what i've tried.这是我尝试过的。
from geopy.distance import geodesic
pd.DataFrame(geodesic(dfa.values[0], dfa.values[0]).kilometers, index=dfa.index, columns=dfa.index)
# i don't know how to change [0] adjusted to column and index
any suggestion?有什么建议吗?
Given a list or list-like object locations
, you can do给定一个列表或类似列表的 object locations
,您可以执行
distances = pd.DataFrame([[geodesic(a,b) for a in locations]
for b in locations])
This will be redundant, though, since it will calculate distance for both a,b and b,a, even though they should be the same.但是,这将是多余的,因为它将计算 a,b 和 b,a 的距离,即使它们应该相同。 Depending on the cost of geodesic
, you may find the some of the following alternatives faster:根据geodesic
的成本,您可能会更快地找到以下一些替代方案:
distances = pd.DataFrame([[geodesic(a,b) if a > b else 0
for a in locations]
for b in locations])
distances = distances.add(distances.T)
size = len(locations)
distances = pd.DataFrame(columns = range(size), index = range(size))
def get_distance(i,j):
if distances.loc[j,i]:
return distances.loc[j,i]
if i == j:
return 0
return geodesic(locations[i], locations[j])
for i in range(size):
for j in range(size):
distances.loc[i,j] = get_distance(i,j)
You can also store the data as a dictionary with the keys being output from itertools.combinations
.您还可以将数据存储为字典,其中键为来自itertools.combinations
的 output。 There's also this article on creating a symmetric matrix class.还有这篇关于创建对称矩阵 class 的文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.