如何向networkx中的节点添加属性

2024-10-01 00:17:51 发布

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

我有两个文件。第一个文件具有边和权重,格式如下:

1    3     1
2    4     1
2    5     1 etc

第二个文件有节点id和节点的属性:

^{pr2}$

使用第一个文件,我使用以下代码创建有向图:

G = nx.read_edgelist('myGraph.txt', create_using=nx.DiGraph(), delimiter='\t', nodetype=int, data=(('sign', int),))

接下来我用第二个文件来读每一行。我读取第一个标记(node id),检查这个节点是否属于我的图节点,然后再次使用split函数删除逗号。现在我想将属性保存到node。我使用下面的代码,但是属性保持空白。这是我的代码:

for line in file2:
    words = line.split()
    node = words[0]
    attributes = words[1]
    splittedAttributes  = attributes.split(',')
    G.node[node]['Attributes'] = splittedAttributes 

Tags: 文件代码idnode属性节点格式line
1条回答
网友
1楼 · 发布于 2024-10-01 00:17:51

你的代码有一个小错误:

G = nx.read_edgelist('myGraph.txt', create_using=nx.DiGraph(), delimiter='\t', nodetype=int, data=(('sign', int),))

nodetype=int您正在以int的形式加载节点。因为linestr,那么{}也是str。如果要使用ints,请执行以下操作:

^{pr2}$

这应该能解决问题。记住以G.node[node]['Attributes']而不是G[node]['Attributes']的形式访问属性,因为这样会输出节点node和{}的权重,这会引发错误。在

相关问题 更多 >