如何将功能添加到networkx中的所有节点



如何分配0-1之间的数字,确定每个邻居的状态。(也就是说,原则上,每个节点都有一个与其关联的数字(状态(!所以当我调用一个节点时;它有它的邻居及其相应州的信息!类似于C中的多维数组!

所以最终的信息是这样的;节点5具有4个邻居,它们是1、2、3、4,每个邻居的状态为0.1、0.4、0.6、0.8。我将在计算中进一步使用这些状态,因此最好使用包含这些信息的数组。

import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
G = nx.barabasi_albert_graph(100,2)
for u in G.nodes():
neighbors = nx.neighbors(G, u)
print(neighbors)

我建议使用字典,其中键是节点的邻居,值是邻居的状态,作为节点的属性。

参见以下几行中的示例:

import networkx as nx
import numpy as np
G = nx.barabasi_albert_graph(100,2)
neighbors={node:{neighbor:np.random.random() for neighbor in G.neighbors(node)} for node in G.nodes()}
nx.set_node_attributes(G, neighbors, 'neighbors')

然后,您可以通过调用G.nodes[0]['neighbors'](此处为节点0的属性(来获取该属性。输出将给出:

{1: 0.7557385760337151, 2: 0.4739260575718104, 3: 0.9567801157103797, 6: 0.7574951042301828, 15: 0.30944298200257603, 20: 0.43632108378325585, 23: 0.36243300334095774, 26: 0.019615624900670037, 33: 0.555648986173134, 47: 0.6303121800990674, 49: 0.5832499539552732, 54: 0.4938474173850117, 80: 0.38306733444449415, 96: 0.19474203458699768}

最新更新