【问题标题】:Python Dataframe calculate Distance via intermediate pointPython Dataframe通过中间点计算距离
【发布时间】:2020-06-13 13:10:02
【问题描述】:

我有一个 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

其中点 1==> 点 2 = From point1 ==> B + From B==> point2 并且包含在a中

如何使用 python 有效地做到这一点 - 我假设某种 pd.merge?

然后我想将数据框重新格式化为以下内容

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

【问题讨论】:

  • 'Distance via B' 是什么意思?

标签: python dataframe dictionary distance reshape


【解决方案1】:

如果您正在寻找长度为 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

【讨论】:

  • 您介意为后代接受答案吗?
猜你喜欢
  • 2020-01-19
  • 2021-11-21
  • 1970-01-01
  • 2013-12-16
  • 2014-11-29
  • 2023-01-26
  • 1970-01-01
  • 2014-02-28
  • 2010-10-30
相关资源
最近更新 更多