Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select network nodes with a given attribute value

I'd like to select and perform operations on nodes within a graph with particular attributes. How would you select nodes with a given attribute value? For example:

P=nx.Graph()
P.add_node('node1',at=5)
P.add_node('node2',at=5)
P.add_node('node3',at=6)

Is there a way to select only the nodes with at == 5?.

I'm imagining something like (this doesn't work):

for p in P.nodes():
    P.node[p]['at'==5]
like image 814
atomh33ls Avatar asked Aug 10 '15 14:08

atomh33ls


People also ask

What are the attributes of nodes?

Node attributes are a special type of option (name-value pair) that applies to a node object. Beyond the basic definition of a node, the administrator can describe the node's attributes, such as how much RAM, disk, what OS or kernel version it has, perhaps even its physical location.

How do you add a node feature to a Networkx graph?

Node attributes nodes does not add it to the graph, use G. add_node() to add new nodes. Similarly for edges.

How do I use Networkx in Python?

Create Graph Now you use the edge list and the node list to create a graph object in networkx . Loop through the rows of the edge list and add each edge and its corresponding attributes to graph g . Similarly, you loop through the rows in the node list and add these node attributes.

How do I add edges to Networkx?

Add an edge between u and v. The nodes u and v will be automatically added if they are not already in the graph. Edge attributes can be specified with keywords or by directly accessing the edge's attribute dictionary.


2 Answers

Python <= 2.7:

According to the documentation try:

nodesAt5 = filter(lambda (n, d): d['at'] == 5, P.nodes(data=True)) 

or like your approach

nodesAt5 = [] for (p, d) in P.nodes(data=True):     if d['at'] == 5:         nodesAt5.append(p) 

Python 2.7 and 3:

nodesAt5 = [x for x,y in P.nodes(data=True) if y['at']==5] 
like image 148
wenzul Avatar answered Sep 22 '22 12:09

wenzul


Sample code if someone is stuck

import networkx as nx  P=nx.Graph() P.add_node('node1',at=5) P.add_node('node2',at=5) P.add_node('node3',at=6)  # You can select like this selected_data = dict( (n,d['at']) for n,d in P.nodes().items() if d['at'] == 5) # Then do what you want to do with selected_data print(f'Node found : {len (selected_data)} : {selected_data}') 
like image 23
Abhi Avatar answered Sep 22 '22 12:09

Abhi