Remove all nodes that has a particular attribute in networkx

Question:

I`m trying to remove all nodes within a Graph that has an specific attribute value.

I have seen this: python networkx remove nodes and edges with some condition

But in that case the degree is a property and not an attribute.

My graph has an attribute call "Line" which could have different values like: A, B, C.

So for example I want to remove all nodes with attribute "Line" equal to A

Asked By: FG85

||

Answers:

You can filter nodes in your graph with a subgraph view:

filter_node = lambda node: G.nodes[node]['Line'] == 'A'
filtered_nodes = list(nx.subgraph_view(G, filter_node=filter_node).nodes)

You can then remove these nodes from the graph:

G.remove_nodes_from(e)
Answered By: Tom McLean
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.