python networkx remove nodes and edges with some condition
If we have an initialized graph g
the following will set f
to be g
subject to the constraint that each vertex must have a degree > 0. We could easily generalize 0 with a variable:
f = nx.Graph()
fedges = filter(lambda x: g.degree()[x[0]] > 0 and g.degree()[x[1]] > 0, g.edges())
f.add_edges_from(fedges)
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]
Note that in Aric's for networkx==2.2, you need to wrap G.degree()
in a dictionary because the networkx view object doesn't have an items method. This line would be:
[node for node,degree in dict(G.degree()).items() if degree > 2]