计算仅包含networkx中具有特定属性的边的节点的程度

时间:2015-05-06 13:17:12

标签: python networkx

我的图表中的所有边都有一个属性,比如说' color'。我想要图中节点的度数,但只计算边缘的颜色' ='红色'

bashrc

所以我希望include bashrc 提供G.add_edges_from([(1,2),(3,4),(4,5)], color='red') G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')

2 个答案:

答案 0 :(得分:2)

对于这种情况,这里有一种方法可以在不制作图表副本的情况下进行。相反,它会创建一个新函数来计算度数。

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})

答案 1 :(得分:0)

我无法找到内置方法,但您可以使用列表推导并通过测试属性值((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}