简体   繁体   中英

Python: read adjacency matrix from file with networkx

I try to read adjacency matrix from file with .dat extension, where data looks like

0   1   1   1   1   1
1   0   1   1   1   1
1   1   0   1   1   1
1   1   1   0   1   1
1   1   1   1   0   1
1   1   1   1   1   0

(it's only part of file, there are 128 strings). I use networkx to read file and to do next operations, but after reading I use

g = nx.read_adjlist("adjacency_matrix/Cont_matr-1.dat")
print(g.number_of_nodes())

I get 2 . But this number more than 2 . Maybe it's wrong way of reading file?

You're reading it in as an adjacency list, not an adjacency matrix. So it's looking just at the first two entries of each line as the nodes.

So the first line is interpreted as an edge between 0 and 1 (with extra information tacked on). The second line is interpreted as an edge between 1 and 0. The third line is an edge between 1 and 1. Etc.

You can convert your matrix into a numpy matrix and then use from_numpy_matrix to read it in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM