简体   繁体   中英

Get the attribute of neighbor node in networkx graph python

I would like to get the attribute of the neighboring node of the networkx graph.

import networkx as nx
G=nx.DiGraph()
G.add_node(10, time = '1PM')
G.add_node(20, time = '5PM')
G.add_node(30, time = '10PM')

G.add_edges_from([(10,20),(20,30)])

I would like to know the attribute of 20 from node 10 or 30, the attribute of 10 from node 20.

This is how I started to approach but couldn't figure out it.

For node1, node2 in G.nodes(data =True):
    print (G.neighbors(node1)['time'])

Is there any way to do this? I appreciate your help.

You can get an iterator over neighbors of node x with G.neighbors(x) . For example, if you want to know the "time" parameter of each neighbor of x you can simply do this:

for neighbor in G.neighbors(x):
    print(G.nodes[neighbor]["time"])

Since you're using a DiGraph , only outgoing edges are kept into account to get the neighbors, that is:

print(list(G.neighbors(10))) # [20]
print(list(G.neighbors(20))) # [30]
print(list(G.neighbors(30))) # []

Instead, in a Graph both incoming and outgoing edges are used:

print(list(G.neighbors(10))) # [20]
print(list(G.neighbors(20))) # [10, 30]
print(list(G.neighbors(30))) # [20]

You can loop through the nodes in DiGraph and get the predecessors and successors list.

Note : G.neigbors doesn't work in your case as the Graph is Directed and it only stores the successors list.

for node in G.nodes:
    try: print('Attribute of {0} from {1}: {2}'.format(node, list(G.predecessors(node))[0], G.node[node]['time']))
    except: pass
    try: print('Attribute of {0} from {1}: {2}'.format(node, list(G.successors(node))[0], G.node[node]['time']))
    except: pass
Attribute of 10 from 20: 1PM
Attribute of 20 from 10: 5PM
Attribute of 20 from 30: 5PM
Attribute of 30 from 20: 10PM

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