Question

I have a dataset that I'm uploading as a graph for various timeframes and trying to figure relationships between them.

I want to delete all the nodes that do not have edges but I'm not sure the command to remove or delete nodes. Any idea how to do this?

Was it helpful?

Solution

import networkx as nx
import matplotlib.pyplot as plt

G=nx.Graph()
G.add_edges_from([('A','B'),('A','C'),('B','D'),('C','D')])
nx.draw(G)
plt.show()

enter image description here

G.remove_node('B')
nx.draw(G)
plt.show()

enter image description here

To remove multiple nodes, there is also the Graph.remove_nodes_from() method.

OTHER TIPS

Documentation covers it.

Graph.remove_node(n): Remove node n.

Graph.remove_nodes_from(nodes): Remove multiple nodes.

For example:

In : G=networkx.Graph()

In : G.add_nodes_from([1,2,3])

In : G.nodes()
Out: [1, 2, 3]

In : G.remove_node(2)

In : G.nodes()
Out: [1, 3]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top