python-3.x - 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.
解决方案
在您的示例中,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'
所以我们为其他人设置权重0
,3
但不为其他任何人设置权重。您也可以一次设置多个属性,但这需要稍微不同的调用。在这里我们有
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: {}})
推荐阅读
- spring-security - 使用几个spring security配置,根据调用url应用
- colors - 悬停功能上的React-elastic-carousel箭头自定义颜色?
- html - 如何在按钮单击时从下拉列表中传递多个值
- php - Laravel 在循环输入字段中获取旧值
- android - 如何为 budtmo/android-docker 设置自定义 config.ini
- php - 如何从 laradoo 包中的 res.users 模型对用户进行身份验证
- javascript - JSON.parse:JSON 数据的第 1 行第 1 列的意外字符(节点 js)
- wso2 - 在中介序列 WSO2 中将字符串转换为小写
- c# - 具有标识的 ASP.NET 中的 CORS 策略
- c# - C# WebBrowser - 如何让 WebBrowser 显示对 DOM 的更新