partition graph into sungraphs based on node's attribute NetworkX

守給你的承諾、 提交于 2020-01-03 04:39:12

问题


I'm using Networkx to compute some measures of a graph such as diameter, clustering coefficient, etc. It's straight forward how to do this for graph as a whole. What I'm interested in is finding these measures between nodes that have same attribute(say color). I'm thinking if I could partition the graph into different sub graphs, where nodes in each sub graph are of the same color, then I could accomplish go ahead and measure diameter in this sub graph. So my question is: Is there a way to partition a graph into sub graphs which contain nodes of same color?

I would really appreciate any insight.


回答1:


Use Graph.subgraph(nodes)

NetworkX 2.x+:

Demo

import networkx as nx

G = nx.Graph()

G.add_nodes_from([1, 2, 3], color="red")
G.add_nodes_from([4, 5, 6])
G.nodes  # NodeView((1, 2, 3, 4, 5, 6))

# create generator
nodes = (
    node
    for node, data
    in G.nodes(data=True)
    if data.get("color") == "red"
)
subgraph = G.subgraph(nodes)
subgraph.nodes  # NodeView((1, 2, 3))

older NetworkX's

Iterate over (Graph.iter_nodes()) and filter the nodes based on your criteria. Pass that list to Graph.subgraph() and it'll return a copy of those nodes and their internal edges.

For example:

G = nx.Graph()
# ... build or do whatever to the graph
nodes = (n for n, d in G.nodes_iter(data=True)) if d.get('color') == 'red')
subgraph = G.subgraph(nodes)


来源:https://stackoverflow.com/questions/28653524/partition-graph-into-sungraphs-based-on-nodes-attribute-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!