Skip to content Skip to sidebar Skip to footer

Changing Attributes Of Nodes

I have the following network: G = nx.Graph() G.add_node(0, weight=8) G.add_node(1, weight=5) G.add_node(2, weight=3) G.add_node(3, weight=2) G.add_node(4, weight=1) G.add_node(5, w

Solution 1:

I made you a crazy list comprehension (because they are cool):

newWeights = \
    [
        sum( # summ for averaging
            [G.nodes[neighbor]['weight'] for neighbor in G.neighbors(node)] # weight of every neighbor
            + [G.nodes[i]['weight']] # adds the node itsself to the average
        ) / (len(list(G.neighbors(node)))+1) # average over number of neighbours+1iflen(list(G.neighbors(node))) > 0# if there are no neighbourselse G.nodes[i]['weight'] # weight stays the same if no neighboursfor i,node inenumerate(G.nodes) # do the above for every node
    ]
print(newWeights) # [6.5, 5.333333333333333, 5.25, 5.0, 1, 4.0, 4.333333333333333]for i, node inenumerate(G.nodes):
    G.nodes[i]['weight'] = newWeights[i] # writes new weights after it calculated them all.

But if you hate fun and list comprehensions you can also use this version:

newWeights = []
for i,node inenumerate(G.nodes): # calculates average for every node
    summation = G.nodes[i]['weight'] # weight of node itsselffor neighbor in G.neighbors(node): # adds the weight of every neighbour
        summation += G.nodes[neighbor]['weight']
    average = summation / (len(list(G.neighbors(node)))+1) # division for average 
    newWeights.append(average) 

print(newWeights)
for i, node inenumerate(G.nodes):
    G.nodes[i]['weight'] = newWeights[i]

Post a Comment for "Changing Attributes Of Nodes"