Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through node attributes in networkx

I create a graph with networkx and every node has some attributes. So i want to search all nodes for a specific attributes and save every node who has this attribute in a list. I wrote the following code but im getting an error:

for node in G.nodes():
    for attribute in G.node[node]['attributes']:
        if attribute in question:
            setOfUsers.append(node)

With this code im getting the following error:

for attribute in G.node[node]['attributes']:
KeyError: 'attributes'

So i search the forum and i tried something different to fix the problem:

for node, data in G.nodes(data=True):
    if data['attributes'] == question[0]:
        setOfUsers.append(node)

but i have the same error. How can iterate through the attributes?

Update: I add the node attributes with the code below. I read the attributes from a file, i split commas and newline character and then i save list in nodes

for line in file2:
    line = line.strip()
    words = line.split('\t')
    node = int(words[0])
    attributes= words[1]
    splittedAttributes = attributes.split(',')
    if node in G.nodes():
        G.node[node]['attributes'] = splittedAttributes
like image 869
Lee Yaan Avatar asked Feb 10 '18 14:02

Lee Yaan


People also ask

What is Nbunch in NetworkX?

nbunch. An nbunch is a single node, container of nodes or None (representing all nodes). It can be a list, set, graph, etc.. To filter an nbunch so that only nodes actually in G appear, use G.

What is AtlasView?

An AtlasView is a Read-only Mapping of Mappings. It is a View into a dict-of-dict data structure. The inner level of dict is read-write. But the outer level is read-only. See also AdjacencyView.

What is a DiGraph in NetworkX?

A DiGraph stores nodes and edges with optional data, or attributes. DiGraphs hold directed edges. Self loops are allowed but multiple (parallel) edges are not. Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention None is not used as a node.

How many nodes can NetworkX handle?

For NetworkX, a graph with more than 100K nodes may be too large. I'll demonstrate that it can handle a network with 187K nodes in this post, but the centrality calculations were prolonged. Luckily, there are some other packages available to help us with even larger graphs.


1 Answers

are your sure you have added the info to your nodes previously? it seems like networkX doesn't known anything about your 'attributes'. by adding the info i mean something like this:

for node in G.nodes():
    G.node[node]['attributes']= attributes[node]

then you can use your own code to examine them

for node in G.nodes():
    for attribute in G.node[node]['attributes']:
        if attribute in question:
            setOfUsers.append(node) 
like image 171
Hamed Temsah Avatar answered Oct 18 '22 14:10

Hamed Temsah