I would like to partition edges of a graph g
based on edge attributes, using Python and NetworkX. In this snippet:
import networkx as nx
g = nx.Graph()
g.add_node(1, pos=[0, 0])
g.add_node(2, pos=[0, 2])
g.add_node(3, pos=[1, 1])
g.add_node(4, pos=[2, 1])
g.add_edge(1, 3, cat='a')
g.add_edge(4, 3, cat='a')
g.add_edge(1, 2, cat='b')
g.add_edge(4, 2, cat='b')
I would like to partition graph g
into graphs ga
and gb
based on cat
attribute and retain node attribute pos
. Note that nodes 1
and 4
will belong to both ga
and gb
. Is there a library support for this operation?
you could use a combination of list comprehension and sets:
ga = g.subgraph(set(*[[u,v] for (u,v,data) in g.edges(data=True) if data.get('cat')=='a']))
gb = g.subgraph(set(*[[u,v] for (u,v,data) in g.edges(data=True) if data.get('cat')=='b']))
This seems to be a simple solution:
ga = g.edge_subgraph(e for e in g.edges() if g.edges[e]['cat']=='a')
gb = g.edge_subgraph(e for e in g.edges() if g.edges[e]['cat']=='b')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.