我有一个矩阵如下:
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 的无向图。我感觉我的源和目标是错误的。
最佳答案
将邻接矩阵重组为边列表。这是使用 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)
关于python - Networkx 没有从邻接矩阵返回漂亮的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59269810/