将edgelist数据转换为networkx obj

2024-04-20 03:03:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件看起来像-

1 2 1
1 3 1
2 999 1
2 1029 1
2 1031 1
2 1032 1
2 1197 1
2 1226 1
2 1296 1
3 450 1
3 933 1
3 934 1
3 955 1
3 1032 1
4 5 1

我想把它转换成networkx图形,但是我得到了以下错误-

^{pr2}$

这是密码-

fh=open("YST_full.net", 'rb')
G=nx.read_edgelist(fh)
fh.close()

我做错什么了?在

edit-I尝试将其转换为pandas dataframe

df=pd.read_csv("YST_full.net",sep=" ",names=['node1','node2','weight'])
print(df)

G=nx.from_pandas_edgelist(df, 'node1', 'node2', ['weight'])

现在我想把它转换成graphml格式-

nx.write_graphml(G, "YST_full.graphml")

但错误是-

    nx.write_graphml(G, "YST_full.graphml")
  File "<decorator-gen-440>", line 2, in write_graphml_lxml
  File "E:\anaconda\lib\site-packages\networkx\utils\decorators.py", line 227, in _open_file
    result = func_to_be_decorated(*new_args, **kwargs)
  File "E:\anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 149, in write_graphml_lxml
    infer_numeric_types=infer_numeric_types)
  File "E:\anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 596, in __init__
    self.add_graph_element(graph)
  File "E:\anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 658, in add_graph_element
    T = self.xml_type[self.attr_type(k, "edge", v)]
KeyError: <class 'numpy.int64'>

Tags: inpynetworkxlibpackageslinesiteanaconda
3条回答

您必须通知networkx第三列是一个名为“weight”的属性(或您称之为“weight”):

graph = nx.read_edgelist("YST_full.net", data=(('weight', float),))

就您的第二个问题而言,有时networkx在导出到GraphML之前,无法将NumPy int64转换为Python int。你必须自己动手:

^{pr2}$

此错误是由于pandas数据帧的数据类型造成的。解决方法是将dataframe列转换为string dtype。在

df = df.apply(lambda x: x.astype(str))
G=nx.from_pandas_edgelist(df, 'node1', 'node2', 'weight')
nx.write_graphml(G,'test.out')

输出:

^{pr2}$

今天我开始学习网络分析,这是我遇到的第一个错误。我刚把G=nx.read_edgelist(fh)改为G=nx.read_weighted_edgelist(fh)。在

也可以删除第三列并使用G=nx.read_edgelist(fh)

相关问题 更多 >