简体   繁体   English

使用networkx从图形中删除边

[英]Remove edges from a graph using networkx

I am trying to convert a DiGraph into n-ary tree and displaying the nodes in level order or BFS. 我试图将DiGraph转换为n元树,并以级别顺序或BFS显示节点。 My tree is similar to this, but much larger, for simplicity using this example: 为了简单起见,我的树与此类似,但更大:

G = networkx.DiGraph()
G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')])
G.add_edges_from([('n4', 'n41'), ('n1', 'n11'), ('n1', 'n12'), ('n1', 'n13')])
G.add_edges_from([('n2', 'n21'), ('n2', 'n22'), ('n', 'n22')])
G.add_edges_from([('n13', 'n131'), ('n22', 'n221'), ('n', 'n131'), ('n', 'n221')])

Tree: borrowed the data from this question and modified it appropriately: 树:从该问题中借用数据并对其进行适当修改:

n---->n1--->n11
 |     |--->n12
 |     |--->n13
 |-----------|--->n131 
 |--->n2              
 |     |---->n21     
 |     |---->n22     
 |------------|--->n221 
 |--->n3

Now my real data set is much more complicated with hundreds of node, to keep it simple I have used the above diagram. 现在,我的实际数据集比数百个节点复杂得多,为简单起见,我使用了上面的图表。

I want remove the unnecessary edges from the tree, such that if a parent has an edge to the child, which has another edge to a grandchild AND the parent also has an edge to the grandchild. 我想从树中删除不必要的边缘,这样,如果父对象对孩子有边缘,孙子边缘对孙子有另一个边缘,而父母对孙子也有边缘。 I simple want to remove the edge between the grandchild and the parent (root), since this is complicating my graph. 我简单地想删除孙子项与父项(根)之间的边缘,因为这会使我的图形复杂化。 ex: I want to remove ('n', 'n131') and ('n', 'n221') from the above graph. 例如:我想从('n', 'n131')删除('n', 'n131')('n', 'n221') What is the best way to achieve this. 实现此目标的最佳方法是什么。

看起来你想找到图G的最小生成树,您可以使用普里姆的或Kruskal算法的实现:这里是一个从SciPy的: http://docs.scipy.org/doc/scipy-0.15.1/reference/生成/ scipy.sparse.csgraph.minimum_spanning_tree.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM