Jack Twain
Jack Twain

Reputation: 6372

Mapping from a node's name to its index and vice versa in networkx

Given a networkx graph, is there a way to map from a node's name to its index in the adjacency matrix and vice versa?

I know that G.nodes() returns a list where the index of the node in the list corresponds to its index in the adjacency matrix.

So to map from a node's name to a node's index, I'm doing a very stupid way of storing the node's index in a dictionary and map it by the node's name.

To map from a node index to its name, then I create another dictionary similar to the one before (with the keys and values switched).

Is there a better way to do this?

Upvotes: 9

Views: 12814

Answers (2)

JARS
JARS

Reputation: 1129

For small / moderate graphs, one simple option is to store the node names as a list:

nodes_list = np.array(list(g.nodes()))

To recover the name from the index, e.g:

node_name = nodes_list[4]

To recover the index from the name:

node_id = np.where(nodes_list == "n4")[0][0]

Upvotes: 1

Excalabur
Excalabur

Reputation: 304

Short answer: not as far as I know. I have a bunch of code similar to yours, though with a few improvements.

The first thing you can do is remember that each node has a dictionary hanging on it. G.node[node_name] is a dictionary of whatever you want. You can thus do something like:

G.node[node_name]['index'] = G.nodes().index(node_name)

Which at least hangs the information on the graph, but in the same fragile way as your method: if you modify your graph the behaviour of G.nodes() isn't documented.

A probably-better solution is to use the nodelist kwarg for G.adjacency_matrix. This takes a list of node names and outputs the adjacency matrix in that order. You can thus set up the list in a sensible-for-your-application way, rather than the pseudorandom behaviour of G.nodes(). For instance, you can pass it a sorted list of your nodes (sorted(G.nodes())) if the nodes are named in a useful way.

Upvotes: 5

Related Questions