Python从文件读取以使用networkx创建加权有向图

Jen*_*Jin 5 python matplotlib networkx python-3.x spyder

我是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
...
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*ity 5

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

#FromNodeId  ToNodeId    Weight
 0   1   0.15
 0   2   0.95
 0   3   0.8
Run Code Online (Sandbox Code Playgroud)

然后修改的调用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()
Run Code Online (Sandbox Code Playgroud)

输出:

[(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})]
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明