可在networkx中使用的属性列表

时间:2015-02-02 16:08:30

标签: networkx

我正在使用networkx,无法在任何地方找到边或节点的可用属性列表。我对已分配的属性不感兴趣,但是在创建或编辑节点或边缘时我可以设置/更改的内容。

有人能指出我记录在哪里吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在创建边缘或节点属性时指定它们。由你来决定他们的名字是什么。

import networkx as nx
G=nx.Graph()
G.add_edge(1,2,weight=5)  #G now has nodes 1 and 2 with an edge
G.edges()
#[(1, 2)]
G.get_edge_data(2,1) #note standard graphs don't care about order
#{'weight': 5}
G.get_edge_data(2,1)['weight']
#5
G.add_node('extranode',color='yellow', age = 17, qwerty='dvorak', asdfasdf='lkjhlkjh') #nodes are now 1, 2, and 'extranode'
G.node['extranode']
{'age': 17, 'color': 'yellow', 'qwerty': 'dvorak', 'asdfasdf': 'lkjhlkjh'}
G.node['extranode']['qwerty']
#'dvorak'

或者您可以使用dict定义nx.set_node_attributes的某些属性,并为使用nx.get_node_attributes定义特定属性的所有节点创建一个dict

tmpdict = {1:'green', 2:'blue'}
nx.set_node_attributes(G,'color', tmpdict)
colorDict = nx.get_node_attributes(G,'color')
colorDict
#{1: 'green', 2: 'blue', 'extranode': 'yellow'}
colorDict[2]
#'blue'

同样,还有nx.get_edge_attributesnx.set_edge_attributes

更多信息在networkx教程中为here。在“节点属性”和“边缘属性”标题下大约在此页面的中间位置。可以在“属性”下找到set...attributesget...attributes的具体文档here

答案 1 :(得分:0)

如果要查询图表以查找可能已在各个节点上应用的所有可能属性(对于共同创建的图形,或者随着时间的推移而编辑的图形,这比您想象的更常见) ,然后以下为我做了诀窍:

set(np.array([list(self.graph.node[n].keys()) for n in self.graph.nodes()]).flatten())

这将返回所有可能的属性名称,其中有值归属于图形节点。我已在此处导入numpy as np以使用np.flatten进行(相对)演奏,但我确定有各种香草蟒蛇替代品(例如,请尝试以下itertools.chain方法,如果你需要避免numpy)

from itertools import chain
set(chain(*[(ubrg.graph.node[n].keys()) for n in ubrg.graph.nodes()]))