计算networkx中仅包含具有特定属性的边的节点度
Calculate the degree of nodes only including edges with a specific attribute in networkx
我图中的所有边都有一个属性,比如 'colour'。我想要图中节点的度数,但只计算 'colour'='red'
的边
G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
所以我想G.degree("colour of edge = red")
给{1:1, 2:1, 3:1, 4:2, 5:1}
我找不到内置方法,但您可以使用列表理解并通过测试属性值来构建新图形,(代码片段归因于 this):
In [162]:
G = nx.DiGraph()
G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
SG=nx.Graph( [ (u,v,d) for u,v,d in G.edges(data=True) if d['color'] == 'red'] )
SG.degree()
Out[162]:
{1: 1, 2: 1, 3: 1, 4: 2, 5: 1}
对于这种情况,这里有一种无需复制图表即可完成的方法。相反,它创建了一个新函数来计算度数。
In [1]: import networkx as nx
In [2]: from collections import defaultdict
In [3]: G = nx.Graph()
In [4]: G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
In [5]: G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
In [6]: def colored_degree(G, color):
degree = defaultdict(int)
for u,v in ((u,v) for u,v,d in G.edges(data=True) if d['color']==color):
degree[u]+=1
degree[v]+=1
return degree
...:
In [7]: colored_degree(G, 'red')
Out[7]: defaultdict(<type 'int'>, {1: 1, 2: 1, 3: 1, 4: 2, 5: 1})
In [8]: colored_degree(G, 'blue')
Out[8]: defaultdict(<type 'int'>, {1: 2, 2: 1, 3: 2, 4: 1})
我图中的所有边都有一个属性,比如 'colour'。我想要图中节点的度数,但只计算 'colour'='red'
的边G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
所以我想G.degree("colour of edge = red")
给{1:1, 2:1, 3:1, 4:2, 5:1}
我找不到内置方法,但您可以使用列表理解并通过测试属性值来构建新图形,(代码片段归因于 this):
In [162]:
G = nx.DiGraph()
G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
SG=nx.Graph( [ (u,v,d) for u,v,d in G.edges(data=True) if d['color'] == 'red'] )
SG.degree()
Out[162]:
{1: 1, 2: 1, 3: 1, 4: 2, 5: 1}
对于这种情况,这里有一种无需复制图表即可完成的方法。相反,它创建了一个新函数来计算度数。
In [1]: import networkx as nx
In [2]: from collections import defaultdict
In [3]: G = nx.Graph()
In [4]: G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
In [5]: G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
In [6]: def colored_degree(G, color):
degree = defaultdict(int)
for u,v in ((u,v) for u,v,d in G.edges(data=True) if d['color']==color):
degree[u]+=1
degree[v]+=1
return degree
...:
In [7]: colored_degree(G, 'red')
Out[7]: defaultdict(<type 'int'>, {1: 1, 2: 1, 3: 1, 4: 2, 5: 1})
In [8]: colored_degree(G, 'blue')
Out[8]: defaultdict(<type 'int'>, {1: 2, 2: 1, 3: 2, 4: 1})