【问题标题】:networkx giving wrong adjacency matrix outputnetworkx 给出错误的邻接矩阵输出
【发布时间】:2017-12-03 22:25:58
【问题描述】:
import networkx as nx
import pandas as pd

data1 = { 'node1': [1,1,1,2],
     'node2': [2,3,6,4],
     'weight': [1,1,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])

df1.to_csv('training.csv')

df=pd.read_csv('training.csv')
G=nx.from_pandas_dataframe(df1,'node1','node2','weight')
print df1
Adjtraining = nx.adjacency_matrix(G)
print Adjtraining.todense()    

输出:

[[0 1 1 0 1]
 [1 0 0 1 0]
 [1 0 0 0 0]
 [0 1 0 0 0]
 [1 0 0 0 0]]

但实际输出应该是:

[[0 1 1 0 0 1]
 [1 0 0 1 0 0]
 [1 0 0 0 0 0]
 [0 1 0 0 0 0]
 [0 0 0 0 0 0]
 [1 0 0 0 0 0]]

这是因为我们可以从数据框中看到节点是 1 2 3 4 和 6。节点 5 不在节点列表中。但它仍然应该包含在邻接矩阵中,但它被忽略网络x。

【问题讨论】:

  • 2个问题:1)你们能提供training.csv吗? 2)networkx是否有理由知道节点5的存在?
  • @Joel Oops df1 本来是训练.csv。抱歉!我编辑了它。是的,因为在邻接矩阵中,行和列代表图的节点,那么如果邻接矩阵只有 5 行和 5 列,那么它就像图只有 5 个节点,实际上它有 6 个节点。只是图中没有 5 个节点

标签: python pandas dataframe graph networkx


【解决方案1】:

节点 5 没有出现在图中,因为它是由边列表实例化的。如果您希望将其添加到生成的邻接矩阵中,您仍然可以将其添加到图中。

G = nx.from_pandas_dataframe(df1, 'node1','node2','weight')
G.add_node(5)
adj = nx.adjacency_matrix(G)
print(adj.todense())

[[0 1 1 1 0 0]  
 [1 0 0 0 1 0]  
 [1 0 0 0 0 0]  
 [1 0 0 0 0 0]  
 [0 1 0 0 0 0]  
 [0 0 0 0 0 0]]

矩阵的索引为:

print(G.nodes())
[1, 2, 3, 6, 4, 5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多