Using a square matrix with Networkx but keep getting Adjacency matrix not square
So I'm using Networkx to plot a cooc matrix. It works well with small samples but I keep getting this error when I run it with a big cooc matrix (reason why I can't share a minimum reproductible example):
Traceback (most recent call last):
File "", line 113, in <module>
G = nx.from_pandas_adjacency(matrix)
File "", line 205, in from_pandas_adjacency
G = from_numpy_array(A, create_using=create_using)
File "", line 1357, in from_numpy_array
raise nx.NetworkXError(f"Adjacency matrix not square: nx,ny={A.shape}")
networkx.exception.NetworkXError: Adjacency matrix not square: nx,ny=(74, 76)
This is my code :
G = nx.from_pandas_adjacency(matrix)
# visualize it with pyvis
N = Network(height='100%', width='100%', bgcolor='#222222', font_color='white')
N.barnes_hut()
for n in G.nodes:
N.add_node(n)
for e in G.edges:
N.add_edge((e[0]), (e[1]))
And this is the ouput of my matrix :
Ali Sarah Josh Maura Mort ... Jasmine Lily Adam Ute
Ali 0 3 2 2 ... 0 0 1 0
Sarah 3 0 3 3 ... 0 0 1 0
Josh 2 3 0 4 ... 0 0 1 0
Maura Mort 2 3 4 0 ... 0 0 1 0
Shelly 0 0 0 0 ... 0 0 0 0
... ... ... ... ... ... ... ... ... ...
Nicol 0 0 0 0 ... 0 0 0 0
Jasmine 0 0 0 0 ... 0 0 0 0
Lily 0 0 0 0 ... 0 0 0 0
Adam 1 1 1 1 ... 0 0 0 0
Ute 0 0 0 0 ... 0 0 0 0
[74 rows x 74 columns]
Weirdly, it looks like my matrix is a square (74 x 74).
Any idea what might be the problem ?
1 answer

So I was able to fix my problem by first converting my matrix into a stack.
cooc_matrix = matrix(matrixLabel, texts) matrix = pd.DataFrame(cooc_matrix.todense(), index=matrixLabel, columns=matrixLabel) print(matrix) #This fixed my problem stw = matrix.stack() stw = stw[stw >= 1].rename_axis(('source', 'target')).reset_index(name='weight') print(stw) G = nx.from_pandas_edgelist(stw, edge_attr=True)
How many English words
do you know?
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
how many words do you know
Powered by Examplum