Reputation: 309
I'll write an example to clarify what I mean:
test = nx.Graph()
test.add_edge(0,3)
test.add_edge(1,2)
test.nodes
Out: NodeView((0, 3, 1, 2))
nx.to_numpy_matrix(test)
Out: matrix([[0., 1., 0., 0.],
[1., 0., 0., 0.],
[0., 0., 0., 1.],
[0., 0., 1., 0.]])
So if you check the example above you can see that networkx orders the nodes in the order that you add them to the graph.
The problem is that I need my adjacency matrix to be ordered by the number given to the node. So for my example, the final matrix has to be:
Out: matrix([[0., 0., 0., 1.],
[0., 0., 1., 0.],
[0., 1., 0., 0.],
[1., 0., 0., 0.]])
Moreover, I'm reading the graph from a file that is an edge list.
At the end my real problem is that the indices of the out matrix differ from the ones in the graph. So for my example if I want to check the node 1 in the matrix I have to write matrix[2] as it's the third node i write in the edge list. Does anybody know how could I fix this?
Upvotes: 0
Views: 102
Reputation: 1878
If you know your nodes in advance then you could add them to the graph before adding edges. For example,
>>> G = nx.Graph()
>>> G.add_node(0)
>>> G.add_node(1)
>>> G.add_node(2)
>>> G.add_node(3)
>>> G.add_edge(0,3)
>>> G.add_edge(1,2)
>>> G.nodes
NodeView((0, 1, 2, 3))
>>> nx.to_numpy_matrix(G)
matrix([[0., 0., 0., 1.],
[0., 0., 1., 0.],
[0., 1., 0., 0.],
[1., 0., 0., 0.]])
Or, looking at the API docs, you could simply do,
print(nx.to_numpy_matrix(test, nodelist=[0,1,2,3]))
Output:
[[0. 0. 0. 1.]
[0. 0. 1. 0.]
[0. 1. 0. 0.]
[1. 0. 0. 0.]]
Upvotes: 1