python - 在 Networkx 中使用方阵但不断得到邻接矩阵而不是方阵

标签 python matrix networkx

所以我使用 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)

关于python - 在 Networkx 中使用方阵但不断得到邻接矩阵而不是方阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69349516/

相关文章:

python - 如何从 Python 中的 GLib.GString 获取原始字节?

r - 通过分配不同的矩阵来计算字符的频率

matrix - 在 SWI prolog 中添加两个矩阵

python - 如何从图中删除小组件

python - 简单的肥尾对数分箱

python - Tensorflow DNNClassifier 和 scikit-learn GridSearchCV 问题

python - 这个 python 程序的最后一行同时使用了 "and ' 但我不知道为什么

python - 使用和随机化代理

python - 是否有任何反向 np.dot 函数?

tensorflow - 如何将卷积神经网络从 Keras 模型对象提取到 Networkx DiGraph 对象,并将权重作为边缘属性?