[英]How to add attribute to a node in networkx
我有2個檔案。 第一個文件具有邊緣和權重,並具有以下格式:
1 3 1
2 4 1
2 5 1 etc
第二個文件具有節點標識和節點屬性:
1 attr1,attr2,attr3
2 attr2,attr4
使用第一個文件,我使用以下代碼創建有向圖:
G = nx.read_edgelist('myGraph.txt', create_using=nx.DiGraph(), delimiter='\t', nodetype=int, data=(('sign', int),))
接下來,我使用第二個文件讀取每一行。 我讀取了第一個標記(節點ID),檢查該節點是否屬於我的圖節點,然后再次使用split函數刪除逗號。 現在我想將屬性保存到節點。 我使用以下代碼,但屬性保持空白。 這是我的代碼:
for line in file2:
words = line.split()
node = words[0]
attributes = words[1]
splittedAttributes = attributes.split(',')
G.node[node]['Attributes'] = splittedAttributes
您的代碼中有一個小錯誤:
G = nx.read_edgelist('myGraph.txt', create_using=nx.DiGraph(), delimiter='\t', nodetype=int, data=(('sign', int),))
nodetype=int
您正在將節點加載為int
。 因為line
是str
所以node
也是str
。 如果要使用ints
請執行以下操作:
node = int(words[0])
這應該夠了吧。 記住要以G.node[node]['Attributes']
而不是G[node]['Attributes']
因為這將輸出節點node
和Attributes
的權重,這將引發錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.