I've a random graph created using Netwrokx and I want to delete nodes with degree less than 2 except for 2 user-defined nodes that have degree = 1. To remove all nodes with degree < 2, I could use Networkx's k-core. But I am not sure how to retain the 2 user-defined nodes. For example, the following code generates,
import networkx as nx
import matplotlib.pyplot as plt
# fig 1
G = nx.gnm_random_graph(n=20, m=30, seed=1)
nx.draw(G, with_labels=True, pos=nx.spring_layout(G))
plt.show()
G = nx.k_core(G, k=2)
nx.draw(G, with_labels=True, pos=nx.spring_layout(G))
plt.show()
Figure 1:
Figure 2:
I would like to ask for suggestions on how to retain 2 user-defined nodes: e.g
retain_node_ids = [1,2]
EDIT:
I could use remove_nodes_from as suggested below. But if we delete nodes with degree < 2 we may end up with new nodes, which originally had degree >=2, with degree <2. To repeat the process until no nodes with degree < 2 is found, k-core has been used.



