Removing self-loops from undirected networkx graph

a 夏天 提交于 2020-08-24 06:42:33

问题


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.


回答1:


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

G.remove_edges_from(G.selfloop_edges())

If you're using 2.x try

G.remove_edges_from(nx.selfloop_edges(G))

You need nx.selfloop_edges(G) because G.selfloop_edges() has been deprecated.

If you have a MultiGraph (which for example configuration_model produces), if this doesn't work it's because you have an older release of 2.x with a minor bug. Then you need to convert this into a list

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

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




回答2:


The selfloop methods were deprecated as graph methods in favor of networkx functions in version 2.0.

version 1.x:

G.remove_edges_from(G.selfloop_edges())

version 2.x:

G.remove_edges_from(nx.selfloop_edges(G))



回答3:


The previous method will be deprecated: use nx.selfloop_edges() instead




回答4:


The method remove_edge does what you need. Simply filter for when the edge source and destination are the same:

for u, v in G.edges_iter():
    if u == v: 
        G.remove_edge(u,v)


来源:https://stackoverflow.com/questions/49427638/removing-self-loops-from-undirected-networkx-graph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!