0

I have a graph with hundreds of edges and I want to remove loops like this:

(1, 2)
(1, 3)
(2, 3)

I have tried:

G.remove_edges_from(nx.selfloop_edges(G)) 

But it does not seems to work. Any advices?

ariac
  • 27
  • 6
  • what version of networkx do you have? (try `nx.__version__`) – Joel Feb 21 '22 at 22:21
  • I expect that you're using an older version of networkx in which case this answer probably helps: https://stackoverflow.com/questions/49427638/removing-self-loops-from-undirected-networkx-graph – Joel Feb 21 '22 at 22:22
  • @Joel I have 2.5 – ariac Feb 22 '22 at 07:36

1 Answers1

1

Selfloops are edges of a node to itself. For example, (1,1) or (2,2) are self loops. The example you is a simple cycle, i.e., a closed path were no node appears twice. You can use simple_cycle or find_cycle. For example, you could iteratively use find cycle:

import networkx as nx

G = nx.karate_club_graph()
print(nx.find_cycle(G, orientation="ignore"))
# [(0, 1, 'forward'), (1, 2, 'forward'), (2, 0, 'forward')]
Sparky05
  • 4,692
  • 1
  • 10
  • 27
  • Thanks for the response. this line: nx.find_cycle(G, orientation="ignore") return only first cycle. How to make it remove all? – ariac Feb 22 '22 at 09:24
  • 1
    You could simply add a loop around it. I'm not sure which edge (all, the first, a random), you want to remove to "break the loop". You can do this until the `NetworkXNoCycle` error is thrown. (It may take quite a while). – Sparky05 Feb 22 '22 at 10:15