我有幾千條道路,每條道路都由一到幾個路段組成。對于每個段,都有一個開始和結束節點。如何對它們進行排序,以便獲得道路的起點和終點?一個道路資料的樣本如圖所示。

在知道了道路的起始節點和終止節點后,我想將這些資訊應用到道路的每個段來創建下表。

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])
uj5u.com熱心網友回復:
也許這會給你一個開始。這將進行拓撲排序并按順序列印出段。您必須擴展它以處理多條道路。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315419.html
