我有一个平台形式的传输网络。内容可以描述如下:
Start_Node,Next_Node,End_Node
10,100,1000
100,200,1000
200,1000,1000
20,1000,1000
我想找到start_end节点对之间的所有节点。所以对于上面的例子,它看起来像:
{10_1000: [100,200,1000]
20_1000: [1000]
100_1000: [200,1000]
200_1000: [1000]}
以下是我的尝试(我正在尝试学习python,因此会欣赏该语言中的任何方向)
import pandas as pd
reg = pd.read_csv('nw.csv')
start_node = reg.start.unique()
end_node = reg.end.unique()
hop_dic = {}
for i in start_node:
for j in end_node:
key = str(i) + " - " + str(j)
node = []
iter = 0
for row in reg.itertuples():
while(row[1]==i and row[3]==j and row[2]!=j and iter < 10):
hop_dic[key] = node.append(row[2])
i = row[2]
iter = iter + 1
print "i =",i,"j= ",j,"iter= ",iter
首先这很慢,因为我显然在运行循环并迭代所有节点对的所有行,其次node.append()不起作用,并在hop_dic中将所有值都赋予None。 Iter只是为了避免无限循环,我找不到连接图。
更新
import pandas as pd
reg = pd.read_csv('regularbagfwd.csv')
start_node = reg.start.unique()
end_node = reg.end.unique()
hop_dic = {}
for i in start_node:
for j in end_node:
key = str(i) + " - " + str(j)
iter = 0
reg_sub = reg.loc[reg.end == j]
node = [0]
while(node[-1] != j): #Checking if the last element is the end node
for row in reg_sub.itertuples():
if row[1]==i and row[2]==j: #last element
node.append(row[2])
hop_dic[key] = node
print "i =",i,"j= ",j,"iter= ",iter,"next= ",row[2]
print hop_dic
break
elif row[1]==i and row[2]!=j: #Not last element
node.append(row[2])
hop_dic[key] = node
i = row[2]
print "i =",i,"j= ",j,"iter= ",iter,"next= ",row[2]
print hop_dic
iter = iter + 1
if iter > 500: #I will break the while loop, untidy I know
break
我得到它的工作,我需要在我的列表中添加一个虚拟0,我可以在以后删除,但必须有一个更好的方法。