如何从Python中的pandas dataframe中获取networkx图形的分支作为列表?

2024-09-27 21:27:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据帧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软件包将此数据框绘制为网络图,如下所示: enter image description here

我想从这个网络图中获得唯一场景/分支的列表。 从节点1开始,这里有四个分支

Node1-Node2-Node4-Node8
Node1-Node2-Node5-Node9
Node1-Node3-Node6-Node10
Node1-Node3-Node7-Node11

如何从Python中给定的数据帧中获取上述分支的列表


Tags: 数据fromdf分支node1node5node2node3
1条回答
网友
1楼 · 发布于 2024-09-27 21:27:35

您可以定义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)

输出:

enter image description here

Node1-Node2-Node5-Node9
Node1-Node3-Node6
Node1-Node3-Node7-Node11

相关问题 更多 >

    热门问题