Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

python - Removing self-loops from undirected networkx graph

I have created a graph from list of nodes using networkx. It has self loops. How to remove them? Following is sample:

import networkx as NX
G=NX.Graph()
G.add_edge(1,2)
G.add_edge(1,1)
print (G.edges())

[(1, 2), (1, 1)]

I don't want (1, 1) edges.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(instructions for networkx 1.x below)

If you're using networkx 2.x try

G.remove_edges_from(nx.selfloop_edges(G))

If you have a MultiGraph (which for example configuration_model produces), this may not work if you have an older release of 2.x with a minor bug. If so and you don't want to upgrade, then you need to convert this into a list before removing edges.

G.remove_edges_from(list(nx.selfloop_edges(G)))

This bug has been corrected https://github.com/networkx/networkx/issues/4068.


In version 1.x (when I originally answered this question), it was:

G.remove_edges_from(G.selfloop_edges())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...