我有一个 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 中手机信号塔的距离矩阵。有人可以帮我解决这个问题吗?
请您参考如下方法:
Scipy 的distance_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. ]])
