Petr Petrov
Petr Petrov

Reputation: 4442

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?

Upvotes: 1

Views: 1353

Answers (1)

Joel
Joel

Reputation: 23827

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.

Upvotes: 3

Related Questions