我有一個df如下所示的熊貓資料框:
From To
0 Node1 Node2
1 Node1 Node3
2 Node2 Node4
3 Node2 Node5
4 Node3 Node6
5 Node3 Node7
6 Node4 Node8
7 Node5 Node9
8 Node6 Node10
9 Node7 Node11
df.to_dict() 是:
{'From': {0: 'Node1',
1: 'Node1',
2: 'Node2',
3: 'Node2',
4: 'Node3',
5: 'Node3',
6: 'Node4',
7: 'Node5',
8: 'Node6',
9: 'Node7'},
'To': {0: 'Node2',
1: 'Node3',
2: 'Node4',
3: 'Node5',
4: 'Node6',
5: 'Node7',
6: 'Node8',
7: 'Node9',
8: 'Node10',
9: 'Node11'}}
我使用 networkx 包將這個 Pandas 資料框繪制為網路圖,如下所示:

我想從這個網路圖中獲取獨特場景/分支的串列。這里有四個分支,從 Node1 開始。
Node1-Node2-Node4-Node8
Node1-Node2-Node5-Node9
Node1-Node3-Node6-Node10
Node1-Node3-Node7-Node11
如何從 Python 中的給定 Pandas 資料框中獲取上述分支串列?
uj5u.com熱心網友回復:
您可以定義Recursive Function和保存路徑和列印路徑:
df = pd.DataFrame({
'From':['Node1','Node1', 'Node2', 'Node2', 'Node3', 'Node3', 'Node4', 'Node5', 'Node6', 'Node7'],
'TO' :['Node2','Node3', 'Node4', 'Node5', 'Node6', 'Node7', 'Node8', 'Node9', 'Node10', 'Node11']
})
def prntPath(lst, node, df, lst_vst):
for val in df.values:
if val[0] == node:
lst.append(val[1])
prntPath(lst, val[1], df, lst_vst)
if not lst[-1] in lst_vst:
print('-'.join(lst))
for l in lst: lst_vst.add(l)
lst.pop()
return
lst_vst = set()
prntPath(['Node1'],'Node1', df, lst_vst)
輸出:
Node1-Node2-Node4-Node8
Node1-Node2-Node5-Node9
Node1-Node3-Node6-Node10
Node1-Node3-Node7-Node11
您可以檢查和使用其他圖表,如下所示:
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
from itertools import chain
from networkx.drawing.nx_pydot import graphviz_layout
def prntPath(lst, node, df, lst_vst):
for val in df.values:
if val[0] == node:
lst.append(val[1])
prntPath(lst, val[1], df, lst_vst)
if not lst[-1] in lst_vst: print('-'.join(lst))
for l in lst: lst_vst.add(l)
lst.pop()
return
df = pd.DataFrame({
'From':['Node1','Node1', 'Node2', 'Node3', 'Node3', 'Node5', 'Node7'],
'TO' :['Node2','Node3', 'Node5', 'Node6', 'Node7', 'Node9', 'Node11']
})
g = nx.DiGraph()
g.add_nodes_from(set(chain.from_iterable(df.values)))
for edg in df.values:
g.add_edge(*edg)
pos = graphviz_layout(g, prog="dot")
nx.draw(g, pos,with_labels=True, node_shape='s')
plt.draw()
plt.show()
lst_vst = set()
prntPath(['Node1'],'Node1', df, lst_vst)
輸出:

Node1-Node2-Node5-Node9
Node1-Node3-Node6
Node1-Node3-Node7-Node11
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322322.html
下一篇:根據相鄰的差異值將串列分組
