python - Networkx 没有从邻接矩阵返回漂亮的图

标签 python pandas networkx graph-theory adjacency-matrix

我有一个矩阵如下:

adjacency_matrix = [['A', 1, 1, 0, 2], ['B', 1, 1, 1, 3], ['C', 0, 0, 1, 1]]

它显示 A 在“元素 1”、“元素 2”中,但不在“元素 3”中,因为它有 1、1 和 0。

B 是“元素 1”、“元素 2”和“元素 3”,因为所有值都是 1 等。最后一个值是该子列表中 0 和 1 的总和。

我创建了一个 pandas 数据框以将其保存到 csv 文件中。在保存之前,它会按总和对其进行排序,然后删除最后一列(总和)。

df = pd.DataFrame(adjacency_matrix, columns = ["Name", "Element 1", "Element 2", "Element 3", "Sum"])
df = df.sort_values(by=['Sum'], ascending=False)
df = df.iloc[:, :-1]

我的下一步是使用邻接矩阵并创建一个漂亮的连接图。

G=from_pandas_edgelist(df, source="Name", target=["Name", "Element 1", "Element 2", "Element 3"])
nx.draw_circular(G, with_labels=True)
plt.axis('equal')
plt.show()

我做错了什么?我没有得到“A”连接到元素 1 和元素 2 的无向图。我感觉我的源和目标是错误的。

enter image description here

最佳答案

将邻接矩阵重组为边列表。这是使用 DataFrame.melt 的示例和 DataFrame.query :

df = pd.DataFrame(adjacency_matrix, columns = ["Name", "Element 1", "Element 2", "Element 3", "Sum"])
df = df.sort_values(by=['Sum'], ascending=False)
df = df.iloc[:, :-1]

df_edges = (df.melt(id_vars='Name', var_name='target')
            .query('value==1'))

[输出]

  Name     target  value
0    A  Element 1      1
1    B  Element 1      1
3    A  Element 2      1
4    B  Element 2      1
7    B  Element 3      1
8    C  Element 3      1


G = nx.from_pandas_edgelist(df_edges, source='Name', target='target')
nx.draw_networkx(G)

enter image description here

关于python - Networkx 没有从邻接矩阵返回漂亮的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59269810/

相关文章:

python - python中使用networkX的多向图

python-3.x - networkx:为每个节点设置不同的 alpha?

python - 更新 Python 3.6 的 pip3?

python - 函数调用的结果不是正确的 float 数组。解决

python - Google Calendar API 日期时间格式 python

python - 将 RESTful 输出转换为数据帧的最有效方法

python - 如何从 networkx 中的图形中删除 float ('nan' ) 节点?

python - 在 python 中保存配置文件的最佳实践

python - 如何在 python 中对列表进行列化?

python - 当我在 Pandas 中读取带有 squeeze 设置为 True 的 csv 时,它使数据框不是系列