【问题标题】:Finding the order of the start and end points of a road based on its segments根据路段查找道路起点和终点的顺序
【发布时间】:2021-10-15 04:13:58
【问题描述】:

我有几千条道路,每条道路都由一到几条路段组成。对于每个段,都有一个开始和结束节点。如何对它们进行排序,以便获得道路的起点和终点?一条道路数据的样本如图所示。

在知道了道路的起始节点和结束节点之后,我想将这些信息应用到道路的每个路段以创建下表。


import pandas as pd

data = [['Road_id','Segment_id','Start_node','End_node'], [1,8285,4740,4741], [1,8509,4741,5144], [1,8437, 5016,5017], [1,8447, 5031, 5016], [1, 8520, 5144,5168], [1,9104,5168,4785],[1,8550,5017,4740]]

df = pd.DataFrame(data[1:], columns = data[0]) 

【问题讨论】:

  • 这称为“拓扑排序”。您实际上制作了一个节点图,并查找没有前任或后继者的节点。 Pandas 不会帮助您完成这项任务;您不妨将数据保存在 Python 列表中。

标签: python sql pandas loops


【解决方案1】:

也许这会给你一个开始。这会进行拓扑排序并按顺序打印出段。您必须扩展它以处理多条道路。

data = [
    ['Road_id','Segment_id','Start_node','End_node'], 
    [1,8285,4740,4741],
    [1,8509,4741,5144],
    [1,8437,5016,5017],
    [1,8447,5031,5016],
    [1,8520,5144,5168],
    [1,9104,5168,4785],
    [1,8550,5017,4740]
]

# Reorganize the data a bit.

rows = {}
nexts = {}
starts = set()
ends = set()
for row in data:
    if isinstance(row[0],str):
        title = row
        continue
    rows[row[2]] = row
    nexts[row[2]]=row[3]
    starts.add(row[2])
    ends.add(row[3])

# Find the start without an end, and the end without a start.

start = (starts-ends).pop()
end = (ends-starts).pop()

# Go print out the rows along this route.

node = start
while node in nexts:
    print(rows[node])
    node = nexts[node]

输出:

(1, 8447, 5031, 5016)
(1, 8437, 5016, 5017)
(1, 8550, 5017, 4740)
(1, 8285, 4740, 4741)
(1, 8509, 4741, 5144)
(1, 8520, 5144, 5168)
(1, 9104, 5168, 4785)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    相关资源
    最近更新 更多