One can easily extract a subgraph from a NetworkX graph by specifying a list of nodes, but I couldn't find an efficient way to perform subgraph extraction by edge. For example, to extract the subgraph consists of edges with weights exceeding some user-defined threshold.
Currently I'm doing it in the following way:
## extracts all edges satisfy the weight threshold (my_network is directed):
eligible_edges = [(from_node,to_node,edge_attributes) for from_node,to_node,edge_attributes in my_network.edges(data=True) if edge_attributes['weight'] > threshold]
new_network = NetworkX.DiGraph()
new_network.add_edges_from(eligible_edges)
Is there a better way to do this?
Thanks for your kind answers.
That looks like the best solution.
You can save memory by using graph.edges_iter()
instead of graph.edges()
, e.g.
>>> G = nx.DiGraph(((source, target, attr) for source, target, attr in my_network.edges_iter(data=True) if attr['weight'] > threshold))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With