Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Way for Modifying Attributes of Single nodes in Networkx 2.1+

I'm looking for an simple way of modifying the value of a single attribute of a single node inside a NetworkX Graph.

The NetworkX documentation only mentions a function for setting an attribute for all nodes in the graph, e.g.:

nx.set_node_attributes(G, bb, 'betweenness')

This might be appropriate in many situations in which such such an attribute is easy to calculate for all nodes in a graph (like be mentioned betweenness). Likewise, there is an easy way to access single node attributes in NetworkX:

graph.nodes[nodeName][attribute]

However, the attributes accessed this way are read-only.

So what i'm looking for a way to set attributes as simple as reading.

Thanks in advance.

like image 602
lowercaseonly Avatar asked Nov 27 '18 21:11

lowercaseonly


1 Answers

In your example, bb is a dict whose keys are the nodes. You don't need the dict to have a key for all nodes in the graph, just the nodes for which you want to define the attribute. In the example below, I create a graph, and then set the 'weight' of node 0 to be 5 and of node 3 to be 2. This leaves the attributes for the other nodes unaffected, so since they've never been created, they don't exist.

import networkx as nx
G = nx.fast_gnp_random_graph(10,0.2)
nx.set_node_attributes(G, {0:5, 3:2}, 'weight')
G.nodes[0]['weight']
> 5
G.nodes[3]['weight']
> 2
G.nodes[1]['weight']
> KeyError: 'weight'

So we set the weight for 0 and 3 but not any of the others. You could also set more than one attribute at once, but that requires a slightly different call. Here we have

nx.set_node_attributes(G, {1:{'weight':-1, 'volume':4}})
G.nodes[1]['weight']
> -1
G.nodes[1]['volume']
> 4

Just to see what the attributes look like after all of that:

G.nodes(data=True)
> NodeDataView({0: {'weight': 5}, 1: {'weight': -1, 'volume': 4}, 2: {}, 3: {'weight': 2}, 4: {}, 5: {}, 6: {}, 7: {}, 8: {}, 9: {}})
like image 147
Joel Avatar answered Jan 01 '23 05:01

Joel