viral
viral

Reputation: 5

Indexing matrix in numpy using Node id

Is there a way to index a numpy matrix, built via networkx as an adjacenjy matrix, using node name (I built the networkx graph parsing lines from a .txt file. Each line represents an edge and it's in the form SourceNode:DestNode:EdgeWeight) I need the matrix because I'm going to calculate the hitting probabilities of some nodes

Upvotes: 0

Views: 717

Answers (1)

Bonlenfum
Bonlenfum

Reputation: 20175

Regardless of how you constructed your graph, you can compute an adjacency matrix of it. The docs state that the order of the rows and columns in this graph will be "as produced by G.nodes()" if you don't specify it.

For example,

# create your graph
G = nx.DiGraph()
with open("spec.txt") as f:
  for line in f:
    for src, dest, weight in line.split(':'):
      G.add_edge(src, dest, weight=weight)

# create adjacency matrix
# - store index now, in case graph is changed.
nodelist = G.nodes()
# extract matrix, and convert to dense representation
A = nx.adjacency_matrix(G, nodelist=nodelist).todense()

# normalise each row by incoming edges, or whatever
B = A / A.sum(axis=1).astype(float)

Let us presume that your nodes are labelled alphabetically, C-G. The node ordering is just according to the dictionary hash, and this sequence for me: ['C', 'E', 'D', 'G', 'F']. If you want to look up information from the matrix, you could use a lookup like this:

ix = nodelist.index('D') # ix is 2 here
print A[ix,:] 

Upvotes: 1

Related Questions