missing nodes in node view of graph after randomly removed some nodes

Viewed 66

I created a graph G and I have a node view as following < 0, 1,2,... 100> I randomly removed 20 nodes and the node view of this new graph misses the nodes I removed randomly. to be precise for example , in the new graph there are some nodes missing(since they are removed node view <0,1,3,5,6,7,9 ...100> however, I want this graph to be a new graph having node view such as the following: <0,1,2....80> is there any solution? I tried relabeling, coping the same graph, they didn't work

PS. my nodes have attribute label equal to either 0,1 and i want to preserve them

1 Answers

Here is one approach you can take. After removing your nodes from the graph you can relabel the remaining nodes using nx.relabel_nodes to get the node view you want. See example below:

import networkx as nx
import numpy as np

#Creating random graph
N_nodes=50
G=nx.erdos_renyi_graph(N_nodes,p=0.25)

#Removing random nodes
N_del_nodes=10
del_node_list=np.random.choice(N_nodes,size=N_del_nodes,replace=False)
G.remove_nodes_from(del_node_list)
print('Node view without relabelling:' +str(G.nodes))

#Relabelling graph
label_mapping={list(G.nodes)[j]:j for j in range(N_nodes-N_del_nodes)}
G_rel=nx.relabel_nodes(G, label_mapping) 
print('Node view with relabelling:' +str(G_rel.nodes))

And the output gives:

Node view without relabelling:[0, 1, 2, 5, 6, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 30, 31, 32, 33, 34, 36, 37, 38, 40, 41, 44, 45, 46, 47, 48, 49]
Node view with relabelling:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
Related