【问题标题】:Python Reading from a file to create a weighted directed graph using networkxPython 从文件中读取以使用 networkx 创建加权有向图
【发布时间】:2017-12-30 17:20:19
【问题描述】:

我是 python 和 Spyder 的新手。 我正在尝试使用 networkx 从具有格式的文本文件中读取到图形中:

FromNodeId  ToNodeId    Weight
0   1   0.15
0   2   0.95
0   3   0.8
0   4   0.5
0   5   0.45
0   6   0.35
0   7   0.4
0   8   0.6
0   9   0.45
0   10  0.7
1   2   0.45
1   11  0.7
1   12  0.6
1   13  0.75
1   14  0.55
1   15  0.1
...

我想使用 Networkx 图形格式,可以存储这么大的图形(大约 10k 节点,40k 边)。

import networkx as nx
import matplotlib.pyplot as plt

g = nx.read_edgelist('test.txt', nodetype=int, create_using= nx.DiGraph())

print(nx.info(g))
nx.draw(g)
plt.show()

当我运行这段代码时,什么也没有发生。 我正在使用 Spyder 进行编辑。 你能帮忙吗?谢谢!

【问题讨论】:

  • “什么都没有发生”就像打印功能甚至不打印? nx.read_edgelist(...) 中可能存在未显示的错误。在 cmd 行中尝试。此外,如果您复制并粘贴代码,则会出现错误的缩进,并且您的“G”不会传递给函数,而是“g”。

标签: python python-3.x matplotlib networkx spyder


【解决方案1】:

您的注释第一行带有符号#read_edgelist 默认跳过以# 开头的行):

#FromNodeId  ToNodeId    Weight
 0   1   0.15
 0   2   0.95
 0   3   0.8

然后修改read_edgelist的调用来定义权重列的类型:

import networkx as nx
import matplotlib.pyplot as plt

g = nx.read_edgelist('./test.txt', nodetype=int,
  data=(('weight',float),), create_using=nx.DiGraph())

print(g.edges(data=True))
nx.draw(g)
plt.show()

输出:

[(0, 1, {'weight': 0.15}), (0, 2, {'weight': 0.95}), (0, 3, {'weight':
0.8}), (0, 4, {'weight': 0.5}), (0, 5, {'weight': 0.45}), (0, 6, {'weight': 0.35}), (0, 7, {'weight': 0.4}), (0, 8, {'weight': 0.6}), (0, 9, {'weight': 0.45}), (0, 10, {'weight': 0.7}), (1, 2, {'weight':
0.45}), (1, 11, {'weight': 0.7}), (1, 12, {'weight': 0.6}), (1, 13, {'weight': 0.75}), (1, 14, {'weight': 0.55}), (1, 15, {'weight':
0.1})]

【讨论】:

  • 你知道为什么语法是data=(('weight',float),),吗?我的意思是在内括号后面加一个逗号。我在networkx的文档文件中没有看到解释。或许只是这样写的规矩?
猜你喜欢
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
相关资源
最近更新 更多