![](/img/trans.png)
[英]extracting connected nodes from weighted undirected graph based on the weight of the edges
[英]Count the number of nodes and edges in each subgraph connected to one node in a weighted undirected graph with networkx
让我们考虑一个加权无向图 G。Networkx 是否有一种优化的方法来获得连接到一个焦点节点的每个子图的节点数和边数?
import networkx as nx
import matplotlib.pyplot as plt
listcolor = ['darkblue', 'blue', 'darkred', 'red', 'darkgreen', 'lime', 'gold', 'yellow', 'darkslateblue', 'darkorchid', 'darkorange', 'orange']
G = nx.Graph()
G.add_edge('A', 'B', weight= 1)
G.add_edge('A', 'J', weight= 2)
G.add_edge('K', 'L', weight= 4)
G.add_edge('E', 'F', weight= 7)
G.add_edge('I', 'J', weight= 8)
G.add_edge('B', 'K', weight= 9)
G.add_edge('B', 'E', weight= 17)
G.add_edge('A', 'C', weight= 19)
G.add_edge('H', 'K', weight= 19)
G.add_edge('G', 'H', weight= 20)
G.add_edge('D', 'H', weight= 22)
pos = nx.spring_layout(G, seed=2)
nx.draw(G,node_color = listcolor, with_labels = True)
plt.tight_layout()
plt.axis("off")
plt.show()
例如,我们考虑节点 B:它有三个连接的子图,一个有 5 个节点(包括 K,L,D,H,G),一个有 4 个节点(包括 C,A,J,I)和一个有 2 个节点节点(包括 F,E)。 现在,假设我需要获得相同的子图列表以及每个节点的数量,无论考虑的节点是什么(另一个示例为 K)。 如何从 G 中有效地获取此子图列表及其节点和边数?
感谢Paul Brodersen通过他的快速评论向我展示了解决方案的方法:
import networkx as nx
import matplotlib.pyplot as plt
import copy
def GetSubGAtt(g,fn): # get subgraphs attributes : g: a graph, fn: focal node
wg = copy.deepcopy(g) # working graph
wg.remove_node(fn)
LSubG = list(nx.connected_components(wg)) # get the subgraphs
dictr = {} # a dict of results {neighbor node:number of nodes in its subgraph}
neig = list(g.adj[fn]) # get the neighbors
for i,j in enumerate(LSubG):
l=len(j)
k=set(neig) & set(j)
dictr[list(k)[0]]=len(j)
return dictr
listcolor = ['darkblue', 'blue', 'darkred', 'red', 'darkgreen', 'lime', 'gold', 'yellow', 'darkslateblue', 'darkorchid', 'darkorange', 'orange']
G = nx.Graph()
G.add_edge('A', 'B', weight= 1)
G.add_edge('A', 'J', weight= 2)
G.add_edge('K', 'L', weight= 4)
G.add_edge('E', 'F', weight= 7)
G.add_edge('I', 'J', weight= 8)
G.add_edge('B', 'K', weight= 9)
G.add_edge('B', 'E', weight= 17)
G.add_edge('A', 'C', weight= 19)
G.add_edge('H', 'K', weight= 19)
G.add_edge('G', 'H', weight= 20)
G.add_edge('D', 'H', weight= 22)
result = GetSubGAtt(G,'B')
print(result)
GetSubGAtt() 返回连接到一个焦点节点的子图的字典以及这些子图中的节点数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.