繁体   English   中英

在Python Networkx中的两个节点之间添加按节点的边属性

[英]Adding an edge by node attribute between two nodes in Python Networkx

我正在编写一些python代码在两个节点之间创建一条边,然后从其中一个节点中随机删除2条边,但与其他节点(不是原始的两个节点)一起删除。

现在,我被卡住了(并且已经遍历了所有networkx文档多次)。

我调用/命名了一个节点“ bad_apple_Bad_apple”-我捕获的另一个节点是“ self.most_central_node”中最中心的节点,并使用max函数对其进行了识别。 我似乎无法选择节点对象本身,因此无法使用add_edge()创建边缘。

我敢肯定,我需要解释更多,但是下面是代码。 如果需要,我可以发布更多代码,但我尝试进一步扩展代码文件,以提供一些背景信息。

    self.most_central_node = max(nx.closeness_centrality(self.combined_network))
    print("The node with the max value for closeness centrality in the combined network is: ", self.most_central_node)

    self.bad_apple_node_stuff = self.combined_network['bad_apple_Bad_apple']

    print("This is the bad apple test", self.bad_apple_node_stuff) #This is not printing the node object which means I'm not selecting it. It's printing it's attributes, I think. This is where the issue is.

    self.combined_network.add_edge(self.combined_network.node['bad_apple_Bad_apple'], self.combined_network.node['closeness'==self.most_central_node]) #<<-- this doesnt work, no specific error though

您的代码有一些问题。 在该行中:

self.most_central_node = max(nx.closeness_centrality(self.combined_network))

closeness_centrality实际上返回一个字典,其中节点是键,而它们的中心是值。 您的行只是通过整数或最长字符串之类的节点来选择最大节点。 您应该将其更改为:

close = nx.closeness_centrality(self.combined_network)
from operator import itemgetter
self.most_central_node = max(close.items(), key=itemgetter(1))[0]

最后一行通过它们的接近度值比较所有(节点,接近度)对,然后将关联的节点简单地存储在变量中。

现在,如果您已经知道另一个节点是'bad_apple_Bad_apple' ,则只需发出以下语句:

self.combined_network.add_edge(self.most_central_node, 'bad_apple_Bad_apple')

另请注意,您已经在代码中访问了存储属性的字典:

network.graph

是图形属性的存储位置,例如name

network.node

例如,存储节点属性的位置

network.node['bad_apple_Bad_apple']

将返回带有属性名称及其值的dict

您说您已经阅读了多次文档,但是我强烈建议您阅读本教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM