简体   繁体   中英

networkx in python for removeing nodes

with this code:

$ out_deg = g.degree()
$ to_remove=[n for n in out_deg if out_deg[n] ==1]     
$ g.remove_nodes_from(to_remove)

I get the following error:

Error:
File "C:\Anaconda3\lib\site-packages\networkx\classes\reportviews.py", line 434, in __getitem__
    nbrs = self._succ[n]

KeyError: (0, 0)

I am trying this code too:

$ g.remove_nodes_from(n for n in g.degree() if g.degree[n] == 1)

And I get the same error as above.

now, with this code:

$ g.remove_nodes_from(n for n , degree in g.degree() if degree == 1)

I get the following error:

Error:
  File "C:\Anaconda3\lib\site-packages\networkx\classes\reportviews.py", line 443, in __iter__
    for n in self._nodes:

RuntimeError: dictionary changed size during iteration

Help Please

Remove networkx nodes iteratively

You can also try using the g.remove_node() function iteratively.

First set up an example graph:

graph = nx.Graph()
graph.add_edges_from([(1,2),(3,1),(5,6)])
nx.draw(graph, with_labels=True)
plt.show()

图1

Then remove node iteratively on condition

[graph.remove_node(k) for k,v in graph.degree().items() if v == 1]
nx.draw(graph, with_labels=True)
plt.show()

Figure2

I can't check for sure in networkx 1.x, but for 2.0: g.degree() is not a dict. It's a DegreeView , which is a networkx specific data type.

When you do for n in g.degree() then n becomes tuple pairs where the first entry in the tuple is the node and the second is the degree. So when it tries to remove the node n , you really want it to remove n[0] --- it doesn't have node n . In your case it dies on the first one where it tries to remove node (0,0) which represents node 0 which has degree 0 .

You're almost on the path with g.remove_nodes_from(n for n , degree in g.degree() if degree == 1) , but the problem is that as it loops through this, things get removed from g . Then the next call to g.degree() is operating on a different graph and python isn't happy to loop over things that are changing.

So try

to_remove=[n for n, degree in out_deg if out_deg[n] ==1]  
g.remove_nodes_from(to_remove)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM