[英]How to find edges with common nodes in Graph Networkx?
我有这个图:
G = nx.MultiGraph()
source_nodes = ['A', 'A', 'B', 'D']
target_nodes = ['B', 'C', 'D', 'E']
for u,v in zip(source_nodes, target_nodes):
G.add_edge(u, v)
我得到的边缘是:
(A, B)
(A, C)
(B, D)
(D, E)
如果一条边的目标节点是另一条边的源节点,我想在它们之间创建一条边。 例如,对于上面的示例,新边将是:
(A, D)
和(A, E)
。
我是 Networkx 的新手,我不知道该怎么做...
首先,您使用MultiGraph 。 它不是定向的,也不存储有关源和目标的信息(它们成为相等的连接节点)。 您应该使用DiGraphs或MultiDiGraphs在有向图中存储信息。
NetworkX DiGraphs 和 MultiDiGraphs 具有predecessors
和successors
功能,可以应用于特定节点。 您可以使用它们来检查从前任到后继的边是否存在,如果不存在,则创建它。
import networkx as nx
G = nx.DiGraph() # Not a MultiGraph! (can be MultiDiGraph)
source_nodes = ['A', 'A', 'B', 'D']
target_nodes = ['B', 'C', 'D', 'E']
for u,v in zip(source_nodes, target_nodes):
G.add_edge(u, v)
# For each node
for n in G.nodes:
# We check all predecessors and successors
for p in G.predecessors(n):
for s in G.successors(n):
# If graph has no edge from predecessor to successor
if (p, s) not in G.edges:
print(p, s) # Print, can be removed
# We add this node
G.add_edge(p, s)
如果您不想为所有节点创建边,而是为一组节点创建边,则可以将G.nodes:
在G.nodes:
行for n in G.nodes:
为给定的一组节点,例如:
for n in [1, 2, 3]:
如果只想为一个节点创建边,则不需要主循环:
NODE_ID = 2
# We check all predecessors and successors of a node
for p in G.predecessors(NODE_ID):
for s in G.successors(NODE_ID):
# If graph has no edge from predecessor to successor
if (p, s) not in G.edges:
print(p, s) # Print, can be removed
# We add this node
G.add_edge(p, s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.