Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient extraction of a subgraph according to some edge attribute in NetworkX

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.

like image 208
Moses Xu Avatar asked Jun 04 '13 05:06

Moses Xu


1 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))
like image 109
Aric Avatar answered Sep 18 '22 18:09

Aric