[英]How to get values from specific node attributes in NetworkX with Python
[英]NetworkX remove attributes from a specific node
我在python中遇到了networkX庫的問題。 我構建了一個圖形,用於初始化一些節點,邊緣和屬性。 我還開發了一種方法,可以將具有特定值的特定屬性動態添加到目標節點。 例如:
def add_tag(self,G,fnode,attr,value):
for node in G:
if node == fnode:
attrs = {fnode: {attr: value}}
nx.set_node_attributes(G,attrs)
因此,如果我們打印目標節點的屬性將被更新
print(Graph.node['h1'])
{'color':u'green'}
self.add_tag(Graph,'h1','price',40)
print(Graph.node['h1'])
{'color':u'green','price':40}
我的問題是如何從目標節點中刪除現有屬性? 我找不到任何刪除/刪除屬性的方法。 我發現只是.update方法並沒有幫助。
謝謝
屬性是python詞典,因此您可以使用del
來刪除它們。
例如,
In [1]: import networkx as nx
In [2]: G = nx.Graph()
In [3]: G.add_node(1,color='red')
In [4]: G.node[1]['shape']='pear'
In [5]: list(G.nodes(data=True))
Out[5]: [(1, {'color': 'red', 'shape': 'pear'})]
In [6]: del G.node[1]['color']
In [7]: list(G.nodes(data=True))
Out[7]: [(1, {'shape': 'pear'})]
我想你提出的del方法會起作用。 你給了我一個很好的想法來構建一個像這樣的remove_attribute方法(使用pop):
def remove_attribute(self,G,tnode,attr):
G.node[tnode].pop(attr,None)
其中tnode是目標節點,attr是我們要刪除的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.