简体   繁体   中英

How to add a feature to all the nodes in networkx

How to assign a number between 0-1 determining the sate of each of the neighbours. (That is in principle, each node has a number(state) associated to it; So that when I call a node; it has the information of its neighbours and their corresponding states! something like a Multi-dimmensional array in C!

So that the final information is something like; node 5 has 4 neighbours which are 1,2,3,4 each with a state 0.1,0.4,0.6,0.8. I will further use these states in my calculations, so preferably an array containing this information will work.

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)

I would recommend using a dictionary, with the keys the neighbors of the nodes and the values the states of the neighbors, as attribute to your nodes.

See example below in a few lines:

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')

You can then get the attribute by calling G.nodes[0]['neighbors'] (here attribute of node 0 ). And the output will give:

{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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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