python - 带有 Lat 和 Lon 的 Pandas 数据框行之间的距离矩阵
问题描述
我有一个带有不同蜂窝塔坐标的 Pandas DataFrame,其中一列是纬度,另一列是经度,如下所示:
Tower_Id Latitude Longitude
0. a1 x1 y1
1. a2 x2 y2
2. a3 x3 y3
等等
我需要获取每个蜂窝塔与所有其他蜂窝塔之间的距离,然后是每个蜂窝塔与其最近的相邻塔之间的距离。
我一直在尝试回收塔的位置与我从插值获得的塔的预期位置之间的距离的一些代码(在这种情况下,我有 4 个不同的列,2 个用于坐标,2 个用于预期坐标) . 我使用的代码如下:
def haversine(row):
lon1 = row['Lon']
lat1 = row['Lat']
lon2 = row['Expected_Lon']
lat2 = row['Expected_Lat']
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
km = 6367 * c
return km
我现在无法计算我现在拥有的 DataFrame 中蜂窝塔的距离矩阵。有人可以帮我解决这个问题吗?
解决方案
Scipydistance_matrix
本质上使用广播,所以这里有一个解决方案
# toy data
lendf = 4
np.random.seed(1)
lats = np.random.uniform(0,180, lendf)
np.random.seed(2)
lons = np.random.uniform(0,360, lendf)
df = pd.DataFrame({'Tower_Id': range(lendf),
'Lat': lats,
'Lon': lons})
df.head()
# Tower_Id Lat Lon
#0 0 75.063961 156.958165
#1 1 129.658409 9.333443
#2 2 0.020587 197.878492
#3 3 54.419863 156.716061
# x contains lat-lon values
x = df[['Lat','Lon']].values * (np.pi/180.0)
# sine of differences
sine_diff = np.sin((x - x[:,None,:])/2)**2
# cosine of lat
lat_cos = np.cos(x[:,0])
a = sine_diff [:,:,0] + lat_cos * lat_cos[:, None] * sine_diff [:,:,1]
c = 2 * 6373 * np.arcsin(np.sqrt(d))
输出(c):
array([[ 0. , 3116.76244275, 8759.2773379 , 2296.26375266],
[3116.76244275, 0. , 5655.63934703, 2239.2455718 ],
[8759.2773379 , 5655.63934703, 0. , 7119.00606308],
[2296.26375266, 2239.2455718 , 7119.00606308, 0. ]])
推荐阅读
- javascript - 如何从 Javascript 对象中删除不需要的密钥?
- python - 使用列表创建方程式
- angularjs - AngularJS $LocalStorage 已清除但 setInterval 仍在工作
- string - 如何拆分以下字符串并找出预订ID
- c# - Xamarin 4 中旧的 ListView 和新的 CollectionView 有什么区别?
- buildfire - Buildfire:手机缺口检测
- c - 在从 main 调用的函数中并行化 MPI 代码
- angular - 路由器链接没有加载具有不同占位符的另一个页面。这是正确的方法吗?
- sorting - 使用 StatefulWidget 对 StatefulWidgets 进行排序
- html - 如何在矩形 div 周围环绕/浮动文本