[英]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.我想获取networkx图的相邻节点的属性。
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.我想知道节点 10 或 30 的 20 的属性,节点 20 的 10 的属性。
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)
.您可以使用G.neighbors(x)
获得节点x
的邻居的迭代器。 For example, if you want to know the "time"
parameter of each neighbor of x
you can simply do this:例如,如果您想知道x
的每个邻居的"time"
参数,您可以简单地这样做:
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:由于您使用的是DiGraph
,因此只考虑传出边来获取邻居,即:
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:相反,在Graph
中同时使用传入和传出边:
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.您可以遍历 DiGraph 中的节点并获取predecessors
和successors
列表。
Note : G.neigbors doesn't work in your case as the Graph is Directed and it only stores the successors list.注意: G.neigbors在您的情况下不起作用,因为图形是有向的,它只存储后继列表。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.