Networkx-使用节点属性的子图

时间:2018-11-15 12:25:24

标签: python networkx

我有一组数据,其中的节点具有显示其所属团队名称的属性。我想计算出a)整个网络的统计数据,然后b)每个团队的统计数据,以比较他们的连通性等。(比如说,我是在比较谁向谁发送电子邮件,从而比较团队的联系程度)。是我的示例代码:

ST = nx.Graph()
ST.add_node('A',role = 'sales1')
ST.add_node('B',role = 'sales1')
ST.add_node('C',role = 'sales1')
ST.add_node('D',role = 'sales1')
ST.add_node('E',role = 'sales2')
ST.add_node('F',role = 'sales2')
ST.add_node('G',role = 'sales2')
ST.add_node('H',role = 'sales2')

ST.add_edges_from([('A','B'),
                   ('A','C'),
                   ('A','D'),
                   ('B','D'),
                   ('B','C'),
                   ('C','D'),
                   ('E','F'),
                   ('E','G'),
                   ('E','H'),
                   ('F','H'),
                   ('G','H'),
                   ('A','E'),
                   ('G','D')])

我知道我可以形成一个子图,如下所示:

H = ST.subgraph(['A','B','C','D'])

是否有通过引用node属性设置节点的简便方法?

1 个答案:

答案 0 :(得分:0)

您可以使用itertools.groupby

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

现在from itertools import groupby # Sort the nodes by their role (this is required for the groupby to work) sorted_by_role = sorted(ST.nodes(data=True), key=lambda node_data: node_data[1]["role"]) # Group objects with same role together grouped = groupby(sorted_by_role, key=lambda node_data: node_data[1]["role"]) subgraphs = dict() for key, group in grouped: nodes_in_group, _ = zip(*list(group)) # We don't care about the data here, only the node names subgraphs[key] = ST.subgraph(nodes_in_group) 字典包含图中存在的每个不同角色的子图。这适用于任意数量的角色。