Lee Yaan
Lee Yaan

Reputation: 547

How to add attribute to a node in networkx

I have 2 files. The first file has the edges and the weight and has the following format:

1    3     1
2    4     1
2    5     1 etc

and the second file has the node id and the atrributes of the node:

1    attr1,attr2,attr3
2    attr2,attr4

Using the first file i create the directed graph using the following code:

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

And next i use the second file to read each line. I read the first token(node id), i check if this node belongs to my graph nodes and then i use again the split function to remove the commas. Now i want to save the attributes to node. I use the following code but the attributes remain blank. Here is my code:

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

Upvotes: 1

Views: 3043

Answers (1)

rodgdor
rodgdor

Reputation: 2630

You have a little mistake in your code:

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

nodetype=int you are loading nodes as int. Because line is a str then node is a str too. If you want to work with ints then do the following:

node = int(words[0])

That should do the trick. Remember to access the attributes as G.node[node]['Attributes'] and not as G[node]['Attributes'] because that would output the weight of nodes node and Attributes which should throw an error.

Upvotes: 2

Related Questions