使用 Python Pandas 合并距离矩阵结果和原始索引

Merge distance matrix results and original indices with Python Pandas

我有一个 panda df,其中包含公交车站及其地理位置列表:

    stop_id   stop_lat   stop_lon  
0   1         32.183939  34.917812  
1   2         31.870034  34.819541  
2   3         31.984553  34.782828  
3   4         31.888550  34.790904  
4   6         31.956576  34.898125  

stop_id 不一定是递增的。

使用 sklearn.metrics.pairwise.manhattan_distances 我计算距离并得到一个对称距离矩阵:

array([[0.      , 1.412176, 2.33437 , 3.422297, 5.24705 ],
       [1.412176, 0.      , 1.151232, 2.047153, 4.165126],
       [2.33437 , 1.151232, 0.      , 1.104079, 3.143274],
       [3.422297, 2.047153, 1.104079, 0.      , 2.175247],
       [5.24705 , 4.165126, 3.143274, 2.175247, 0.      ]])

但我现在无法轻松地将两者联系起来。我想要一个 df,其中包含每对停靠点及其距离的元组,例如:

stop_id_1 stop_id_2 distance
1         2         3.33

我尝试使用下方的三角形,转换为矢量等等,但我觉得我只是把事情复杂化了,但没有成功。

df_dist = pd.DataFrame.from_dict(dist_matrix)
pd.merge(df, df_dist, how='left', left_index=True, right_index=True)

example

希望对您有所帮助!

d= '''    stop_id   stop_lat   stop_lon  
0   1         32.183939  34.917812  
1   2         31.870034  34.819541  
2   3         31.984553  34.782828  
3   4         31.888550  34.790904  
4   6         31.956576  34.898125 '''

df = pd.read_csv(pd.compat.StringIO(d), sep='\s+') 

from sklearn.metrics.pairwise import manhattan_distances
distance_df = pd.DataFrame(manhattan_distances(df))

distance_df.index = df.stop_id.values
distance_df.columns = df.stop_id.values
print(distance_df)

输出:

          1         2         3         4         6
1  0.000000  1.412176  2.334370  3.422297  5.247050
2  1.412176  0.000000  1.151232  2.047153  4.165126
3  2.334370  1.151232  0.000000  1.104079  3.143274
4  3.422297  2.047153  1.104079  0.000000  2.175247
6  5.247050  4.165126  3.143274  2.175247  0.000000

现在,要创建相同 df 的长格式,请使用以下命令。

long_frmt_dist=distance_df.unstack().reset_index()
long_frmt_dist.columns = ['stop_id_1', 'stop_id_2', 'distance']
print(long_frmt_dist.head())

输出:

   stop_id_1  stop_id_2  distance
0          1          1  0.000000
1          1          2  1.412176
2          1          3  2.334370
3          1          4  3.422297
4          1          6  5.247050