Networkx无法从熊猫邻接矩阵返回漂亮的图形

时间:2019-12-10 14:45:52

标签: python pandas graph networkx

我有一个如下的矩阵:

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的总和。

我创建了一个熊猫数据框,将其保存到一个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

2 个答案:

答案 0 :(得分:3)

将邻接矩阵重组为边列表。这是使用DataFrame.meltDataFrame.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

答案 1 :(得分:2)

我的方法是重组您的adjacency_matrix以包括所有对:

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

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 = df.set_index('Name')

edges = df.columns

for i in df.index:
    df[i] = [0 for _ in range(len(df.index))]

for e in edges:
    r = [0 for _ in range(len(df.columns))]
    df.loc[len(df)] = r


as_list = df.index.tolist()
as_list[len(adjacency_matrix):] = edges
df.index = as_list


G=nx.from_pandas_adjacency(df)
nx.draw_circular(G, with_labels=True)
plt.axis('equal')
plt.show()

按照以下步骤制作您的df

           Element 1  Element 2  Element 3  B  A  C
B                  1          1          1  0  0  0
A                  1          1          0  0  0  0
C                  0          0          1  0  0  0
Element 1          0          0          0  0  0  0
Element 2          0          0          0  0  0  0
Element 3          0          0          0  0  0  0

哪个给:

enter image description here