可用于NetworkX的属性列表

8

我正在与networkx一起工作,但无法找到有关边缘或节点可用属性的列表。 我不感兴趣的是已经分配了哪些属性,而是在创建或编辑节点或边缘时可以设置/更改哪些属性。

有人能指出这个文档的位置吗?

谢谢!

4个回答

5
如果您想查询图形中应用于各个节点的所有可能属性(对于社区创建的图形或随时间编辑的图形而言,这比您想象的要更普遍),则以下内容对我非常有效:
set(np.array([list(self.graph.node[n].keys()) for n in self.graph.nodes()]).flatten())

这将返回所有可能的属性名称,其中有值被归属于图节点。在这里我导入了 numpy as np 以使用 np.flatten 来提高性能,但我相信有各种普通的Python替代方案(例如,如果您需要避免使用numpy,则可以尝试以下 itertools.chain 方法)。

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

7
这是最基本的代码:set([k for n in g.nodes for k in g.nodes[n].keys()])。我无法理解为什么同样的方法不能用于获取边缘属性;这个方法适用于节点或边缘。 - snooze_bear
@snooze_bear,你的速度快了3倍,也谢谢你。 - Maurício Collaça

3

在创建边缘或节点时,您可以分配许多属性。它取决于您决定它们的名称。

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'

你可以使用字典来定义一些属性,然后用 nx.set_node_attributes 来设置这些属性,使用 nx.get_node_attributes 来获取所有具有特定属性的节点的字典。

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教程的这里找到:这里,在页面的中间位置下方分别是“Node Attributes”和“Edge Attributes”两个小标题。有关set...attributesget...attributes的具体文档可以在此处的“Attributes”章节中找到。

1
在 NetworkX 图中,针对节点属性的唯一值:
# simple version
node_attr = {k for node in GRAPH.nodes for k in GRAPH.nodes[node].keys()}

# efficient version: 3X faster
node_attr = {k for attr_dict in GRAPH.nodes.data()._nodes.values() for k in attr_dict.keys()}

-3
nx.subgraph_view(G, filter_node= lambda n : n in nodes).edges.data(attr)

1
感谢您为Stack Overflow社区做出的贡献。这可能是一个正确的答案,但如果您能提供代码的额外解释,让开发人员能够理解您的推理过程,那将非常有用。对于不太熟悉语法或难以理解概念的新开发人员来说,这尤其有帮助。您是否可以编辑您的答案,包含更多细节,以造福整个社区? - Jeremy Caney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接