首页 > 解决方案 > 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.

标签: python-3.xgraphnetworkx

解决方案


在您的示例中,bb是一个 dict,其键是节点。您不需要 dict 对图中的所有节点都有一个键,只需要为其定义属性的节点即可。在下面的示例中,我创建了一个图形,然后将'weight'of 节点设置0为 be5和 of node3设置为2。这使其他节点的属性不受影响,因此由于它们从未被创建,因此它们不存在。

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'

所以我们为其他人设置权重03但不为其他任何人设置权重。您也可以一次设置多个属性,但这需要稍微不同的调用。在这里我们有

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

只是为了看看这些属性是什么样子的:

G.nodes(data=True)
> NodeDataView({0: {'weight': 5}, 1: {'weight': -1, 'volume': 4}, 2: {}, 3: {'weight': 2}, 4: {}, 5: {}, 6: {}, 7: {}, 8: {}, 9: {}})

推荐阅读