[英]Filter NetworkX graph to list all edges coming from a nodes with specific attributes
I have a NetworkX graph, with various node attributes loaded into the graph. 我有一个NetworkX图,图中已加载了各种节点属性。 I would like to iterate through this graph, and first find all of the nodes that contain the attribute 'metric' : 'Top2'
. 我想遍历此图,首先找到包含属性'metric' : 'Top2'
所有节点。 Then once I have this list, I would like to the edges of all the 'Top2' nodes, and list out any edge that a 'Top2' node has to a node with the attribute 'city': 'Dallas'
' 然后,有了该列表后,我想要所有“ Top2”节点的边缘,并列出“ Top2”节点对具有'city': 'Dallas'
属性的节点的所有边缘'city': 'Dallas'
”
I am able to successfully load my graph and attributes into NetworkX, but I can't seem to figure out how to get the node attribute filtering part figured out like I want to. 我能够成功地将图形和属性加载到NetworkX中,但是似乎无法弄清楚如何像我想要的那样弄清楚节点属性过滤部分。
Ultimately, I want to find any connections where a node with the attribute 'Top2' is in direct contact with a node with the attribute 'Dallas': 最终,我想找到属性为“ Top2”的节点与属性为“ Dallas”的节点直接接触的所有连接:
Code 码
# import module
import networkx as nx
# create a blank graph
g = nx.Graph()
# add nodes with attributes to the graph
n = [(u'A', {'city': 'Dallas'}),
(u'C', {'city': 'Toledo'}),
(u'B', {'city': 'Dallas'}),
(u'E', {'city': 'Toldeo'}),
(u'D', {'city': 'Lousiville', 'metric': 'Top2'}),
(u'G', {'city': 'Lousiville'}),
(u'F', {'city': 'Dallas', 'metric': 'Top2'})]
e = [(u'A', u'B'),
(u'C', u'B'),
(u'B', u'D'),
(u'E', u'D'),
(u'E', u'G'),
(u'E', u'F'),
(u'D', u'G'),
(u'D', u'F'),
(u'G', u'F')]
# add nodes and edges to the graph
g.add_nodes_from(n)
g.add_edges_from(e)
# draw the graph
nx.draw(g)
# iterate through graph to identify all nodes with attribute 'metric' == 'Top2'
Top2_nodes = []
for n in g.nodes(data=True) if n[1]['metric'] == 'Top2'
Top2_nodes.append(n)
# iterate through 'Top2_nodes' to identify their connections to nodes with attribute 'city': 'Dallas'
...
Ideally, the results would be formatted as follows: 理想情况下,结果的格式应为:
D,B
D,F
D,G
This uses 2 helper-functions that return a bool. 这使用2个返回bool的辅助函数。 Your actual result is returned as list comprehension in the end. 最后,您的实际结果将作为列表理解返回。
nodes = g.node
def has_top2(n):
return 'metric' in nodes[n] and nodes[n]['metric'] == 'Top2'
def has_dallas(n):
return 'city' in nodes[n] and nodes[n]['city'] == 'Dallas'
[(n, u) for n, u in g.edges()
if (has_top2(n) and has_dallas(u))
or (has_top2(u) and has_dallas(n))
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.