将方阵与 Networkx 一起使用,但保持邻接矩阵不是方阵

Using a square matrix with Networkx but keep getting Adjacency matrix not square

所以我正在使用 Networkx 绘制 cooc 矩阵。它适用于小样本,但当我 运行 使用大 cooc 矩阵时,我一直收到此错误(我无法共享最小可重现示例的原因):

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)

这是我的代码:

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]))

这是我的矩阵的输出:

            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]

奇怪的是,我的矩阵看起来是一个正方形 (74 x 74)。

知道可能是什么问题吗?

所以我能够通过首先将矩阵转换为堆栈来解决我的问题。

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)