Python 具有Lat和Lon的数据帧行之间的距离矩阵

Python 具有Lat和Lon的数据帧行之间的距离矩阵,python,pandas,distance,Python,Pandas,Distance,我有一个Pandas数据框,其中一列是纬度,另一列是经度,如下图所示: Tower_Id Latitude Longitude 0. a1 x1 y1 1. a2 x2 y2 2. a3 x3 y3 等等 我需要得到每个发射塔和所有其他发射塔之间的距离,然后是每个发射塔和最近的相邻发射塔之间的距离

我有一个Pandas数据框,其中一列是纬度,另一列是经度,如下图所示:

         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

我现在还不能计算我现在拥有的数据帧中的细胞塔的距离矩阵。有人能帮我解决这个问题吗?

Scipy的
距离矩阵
基本上使用广播,所以这里有一个解决方案

# 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):


可能是@Mstaino的副本,但不是。这里距离不是欧几里德的,OP需要距离矩阵。
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.        ]])