Ordered nodes in adjacency matrix when using nx.to_numpy_array

Viewed 807

I create a graph with some edges:

import networkx as nx

g = nx.Graph()
g.add_edge(1, 2)
g.add_edge(2, 6)
g.add_edge(3, 4)
g.add_edge(5, 6)

print(g.edges)
output-> (1, 2), (1, 5), (2, 6), (5, 6), (3, 4)

And then getting adjacent A by making use of graph g

nx.convert_matrix.to_numpy_array(g)

The result is :

array([[0., 1., 1., 0., 0., 0.],
       [1., 0., 0., 1., 0., 0.],
       [1., 0., 0., 1., 0., 0.],
       [0., 1., 1., 0., 0., 0.],
       [0., 0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 1., 0.]])

You can see that adjacent not match g if you regard the indices of elements on adjacent as following:

A :   1 2 3 4 5 6
     —————————————
  1 | 0 1 1 0 0 0
  2 | 1 0 0 1 0 0
  3 | 1 0 0 1 0 0
  4 | 0 1 1 0 0 0
  5 | 0 0 0 0 0 1
  6 | 0 0 0 0 1 0

For example:

On A, the value of indices (1, 3) equal 1, as usual, which means edges (1, 3) is exist, but actually not !

If I change the indices of A to this as below:

A :   1 2 5 6 3 4
     —————————————
  1 | 0 1 1 0 0 0
  2 | 1 0 0 1 0 0
  5 | 1 0 0 1 0 0
  6 | 0 1 1 0 0 0
  3 | 0 0 0 0 0 1
  4 | 0 0 0 0 1 0

the match will be right between edges and A.

My question

How to make A's indices follow the normal order -> 1,2,3,4...

Thanks in advance ~

1 Answers

The order in which the nodes appear as a result of to_numpy_matrix, depends on the insertion order of the edges, which is the order in which the nodes are added to the graph. You can check the actual order of the adjacency matrix with nx.to_pandas_adjacency:

g = nx.Graph()
g.add_edge(1, 2)
g.add_edge(2, 6)
g.add_edge(3, 4)
g.add_edge(5, 6)
g.edges()
# EdgeView([(1, 2), (2, 6), (6, 5), (3, 4)])

nx.to_pandas_adjacency(g)

     1    2    6    3    4    5
1  0.0  1.0  0.0  0.0  0.0  0.0
2  1.0  0.0  1.0  0.0  0.0  0.0
6  0.0  1.0  0.0  0.0  0.0  1.0
3  0.0  0.0  0.0  0.0  1.0  0.0
4  0.0  0.0  0.0  1.0  0.0  0.0
5  0.0  0.0  1.0  0.0  0.0  0.0

To get an adjacency matrix with ordered nodes, you can use the nodelist parameter in nx.to_numpy_matrix, and feed it a sorted list of nodes:

nx.to_numpy_matrix(g, nodelist=sorted(g.nodes()))

matrix([[0., 1., 0., 0., 0., 0.],
        [1., 0., 0., 0., 0., 1.],
        [0., 0., 0., 1., 0., 0.],
        [0., 0., 1., 0., 0., 0.],
        [0., 0., 0., 0., 0., 1.],
        [0., 1., 0., 0., 1., 0.]])

Which is the same you'd get by reindexing the axes in the adjacency dataframe:

nodes_sorted = sorted(g.nodes())
nx.to_pandas_adjacency(g).reindex(index=nodes_sorted, columns=nodes_sorted)

    1    2    3    4    5    6
1  0.0  1.0  0.0  0.0  0.0  0.0
2  1.0  0.0  0.0  0.0  0.0  1.0
3  0.0  0.0  0.0  1.0  0.0  0.0
4  0.0  0.0  1.0  0.0  0.0  0.0
5  0.0  0.0  0.0  0.0  0.0  1.0
6  0.0  1.0  0.0  0.0  1.0  0.0
Related