Python数据帧通过中间点计算距离

Python数据帧通过中间点计算距离,python,dataframe,dictionary,distance,reshape,Python,Dataframe,Dictionary,Distance,Reshape,我有一个python数据帧,其距离如下所示 dict = {'from' : ['A','A','A','B','B','D','D','D'], 'to' : ['B','C','D','C','E','B','C','E'], 'distances': [4,3,1,1,3,4,2,9]} df = pd.DataFrame.from_dict(dict) 我想列举以下各项的所有距离: 从点1==>点2 其中,point1==>point2= From p

我有一个python数据帧,其距离如下所示

dict = {'from' : ['A','A','A','B','B','D','D','D'],
         'to' : ['B','C','D','C','E','B','C','E'],
        'distances': [4,3,1,1,3,4,2,9]}
df = pd.DataFrame.from_dict(dict)
我想列举以下各项的所有距离:

从点1==>点2

其中,point1==>point2= From point1==>B+From B==>point2并包含在a中

如何使用python高效地实现这一点?我假设使用某种pd.merge

然后,我想将数据帧重新格式化为以下格式

columns = ['From','To','Distance','Distance via B']

如果您正在寻找长度为3的路线,这里有一个解决方案。请注意,在某些情况下,直达路线(如A至B)比路线A-B-C短:

three_route = pd.merge(df, df, left_on="to", right_on="from")
three_route["distance"] = three_route.distances_x + three_route.distances_y
three_route = three_route[["from_x", "to_x", "to_y", "distance"]]. \
      rename(columns = {"from_x":"from", "to_x": "via", "to_y": "to"})
结果是:

  from via to  distance
0    A   B  C         5
1    A   B  E         7
2    D   B  C         5
3    D   B  E         7
4    A   D  B         5
5    A   D  C         3
6    A   D  E        10

为了子孙后代,你介意接受这个答案吗?
“通过B的距离”是什么意思?