Home > Software design >  Mapping of string to index value in networkx graph
Mapping of string to index value in networkx graph

Time:10-19

Using Python Networkx, I am creating a graph of cities with their population.

#Graph Creation
my_Graph = nx.DiGraph()
my_Graph.add_nodes_from([
  ("S1", {"Population": 100}),
  ("S2", {"Population": 200}),
  ("S3", {"Population": 300})])

  my_Graph.add_edge("S1", "S2", capacity=50)
  my_Graph.add_edge("S2", "S1", capacity=30)
  my_Graph.add_edge("S2", "S3", capacity=70)
  my_Graph.add_edge("S3", "S2", capacity=50)
  my_Graph.add_edge("S1", "S3", capacity=55)

When I print the list of cities using:

    print("The cities are :", my_Graph.nodes)

my output is

The cities are :['S1', 'S2', 'S3']

I want a mapping function that maps the cities (nodes) to their indices in the network.

CodePudding user response:

Based on your comments, I think this might be what you're after.

Using the built-in convert_node_labels_to_integers, you can do the following (assuming you want to start the labeling at 1 as indicated in your comments):

my_Graph = nx.convert_node_labels_to_integers(my_Graph, first_label = 1)

my_Graph.nodes()
>>>[1, 2, 3]

my_Graph.edges()
>>>[(1, 2), (1, 3), (2, 1), (2, 3), (3, 2)]

Nodes are converted to integers and the edges are kept between the correct nodes with the updated names. The attributes of the nodes and edges are maintained as well if you need them.

  • Related