Python从文件读取以使用networkx创建加权有向图 [英] Python Reading from a file to create a weighted directed graph using networkx
本文介绍了Python从文件读取以使用networkx创建加权有向图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是python和Spyder的新手.我正在尝试使用networkx从具有格式的文本文件中读取图形:
I am new at python and Spyder. I am trying to read from a text file with format into a graph using 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图形格式,该格式可以存储这么大的图形(大约1万个节点,40万个边).
I want to use Networkx graph format that can store such a large graph(about 10k nodes, 40k edges).
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进行编辑.你能帮忙吗?谢谢!
When I run this code, nothing happens. I am using Spyder for editing. Could you help? Thanks!
推荐答案
您的注释第一行带有符号 #
(read_edgelist
默认跳过行以 开头#
):
You have comment first line with symbol #
(read_edgelist
by default skip lines start with #
):
#FromNodeId ToNodeId Weight
0 1 0.15
0 2 0.95
0 3 0.8
然后修改 read_edgelist
的调用以定义重量列的类型:
Then modify call of read_edgelist
to define type of weight column:
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})]
这篇关于Python从文件读取以使用networkx创建加权有向图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文