I have an undirected graph as follows:
import networkx as nx
import matplotlib.pyplot as plt
l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]
G=nx.Graph()
G.add_edges_from(l)
nx.draw_networkx(G,with_labels=True)
plt.show()
I want to combine edges when node satisfies degree=n(like 2)
. I need remove node 1
,2
and 8
,and connect 3-6
and 6-9
in my example. So I expect the results to be as follows.
How can I do it? Thanks in advaence
import networkx as nx
import matplotlib.pyplot as plt
l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]
G=nx.Graph()
G.add_edges_from(l)
# Select all nodes with only 2 neighbors
nodes_to_remove = [n for n in G.nodes if len(list(G.neighbors(n))) == 2]
# For each of those nodes
for node in nodes_to_remove:
# We add an edge between neighbors (len == 2 so it is correct)
G.add_edge(*G.neighbors(node))
# And delete the node
G.remove_node(node)
nx.draw(G,with_labels=True)