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?
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]
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