Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python networkx remove nodes and edges with some condition

In the python library networkx I would like to remove the nodes and edges of a graph which have some property. For example, suppose I wanted to remove all nodes and edges where the degree of a node was < 2. Consider the following psuedocode:

vdict = g.degree_dict()         #dictionary of nodes and their degrees
g.remove_from_nodes(v in g s.t. vdict[v] < 2)

I have seen some syntax that uses set theory notation but as I am still new to python I do not know how to use it. How do I convert this into working python code?

like image 588
CodeKingPlusPlus Avatar asked Aug 15 '13 20:08

CodeKingPlusPlus


1 Answers

The Graph.remove_nodes_from() method takes a list (container actually) of nodes. So you just need to create a list that satisfies your condition. You can use Python's list comprehension structure to compactly create a list of nodes to delete.

In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_edge(1,2)

In [4]: G.add_edge(1,3)

In [5]: G.add_edge(1,4)

In [6]: G.add_edge(2,3)

In [7]: G.add_edge(2,4)

In [8]: G.degree()
Out[8]: {1: 3, 2: 3, 3: 2, 4: 2}

In [9]: remove = [node for node,degree in dict(G.degree()).items() if degree > 2]

In [10]: remove
Out[10]: [1, 2]

In [11]: G.nodes()
Out[11]: [1, 2, 3, 4]

In [12]: G.remove_nodes_from(remove)

In [13]: G.nodes()
Out[13]: [3, 4]
like image 127
Aric Avatar answered Oct 13 '22 01:10

Aric