我没有使用 Python/NetworkX 的经验。我尝试的一切都是死胡同。我在 Windows 8 上安装了 Python 2.7。(花了很长时间才安装 NetworkX。)
A.我无法让 NetworkX 读取我的加权网络
我有一个包含边和权重的文本文件,如下所示:
1 2 2
2 3 1
2 4 1
4 5 4 (…etc.)
我将文件命名为 test.edgelist(正如我在许多示例中看到的那样),然后使用以下代码读取它:
import networkx as nx
fh=open("test.edgelist", 'rb')
G=nx.read_weighted_edgelist(fh, nodetype=int)
fh.close()
我收到以下错误消息:
'module' object has no attribute 'read_weighted_edgelist'
(注意:对于只有前两列的未加权版本,使用相同的代码,只是使用 read_edgelist 而不是 read_weighted_edgelist,它工作得很好)
并且通过使用这个替代代码:
G = nx.read_edgelist("test.edgelist", nodetype=int, data=(("weight",float),))
我收到以下错误消息:
read_edgelist() got an unexpected keyword argument 'data'
B.找不到从文件中读取某些节点属性的方法。
文本文件类似于:
Label Sex Country Colour
1 F GB green
2 M DE red
3 M IT blue (…etc.)
我找到了这个,我认为它与我正在寻找的东西唯一相关:
Reading nodes with pos attribute from file in networkx
虽然 csv 格式对我来说不是问题,但我试了一下并安装了 pandas,但我得到的只是错误:
from pandas.io.api import *
from pandas.io.gbq import read_gbq
import pkg_resources
ImportError: No module named pkg_resources
请您参考如下方法:
A.
如果您的数据在文本文件中,那么您需要将其作为文本而不是二进制文件打开。
import networkx as nx
fh=open("test.edgelist", 'r')
# ------------------------|----- note 'r' not 'rb'
G=nx.read_weighted_edgelist(fh, nodetype=int)
fh.close()
使用您提供的样本数据,这两种方法对我来说都很好。特别令人惊讶的是第二个命令不起作用,这让我想知道你是否覆盖了一个内置命令(参见例如 How to stop myself overwriting Python functions when coding?)。
我使用的是 networkx 1.6 版。 (您可以通过在交互式 shell 中键入 nx.__version__ 来测试它)
B.
Pandas 在读取数据方面非常灵活——它不必以逗号分隔(即使使用 read_csv 函数)。例如,假设您的第二个标记数据集位于文件“data.txt”中,
import pandas as pd
df = pd.read_csv('data.txt', sep='\s')
In [41]: print df
Label Sex Country Colour
0 1 F GB green
1 2 M DE red
2 3 M IT blue
3 NaN None None None
利用这些数据,您可以构建一个图,其节点具有以下属性:
# a new empty graph object
G2 = nx.DiGraph()
# create nodes with properties from dataframe (two examples shown, but any number
# of properties can be entered into the attributes dictionary of each node)
for idx, row in df.iterrows():
G2.add_node(row['Label'], colour=row['Colour'], sex=row['Sex'])
# construct a list of colors from the nodes so we can render with that property
colours = [ d['colour'] for n, d in G2.nodes(data=True)]
nx.draw_networkx(G2, node_color=colours)
我不完全确定您为什么需要 pkg_resources(您链接的答案中似乎没有使用它),但请参阅 No module named pkg_resources如何解决错误。
