我在 NetworkX 中有一个有向图。边缘的权重从 0 到 1,表示它们发生的概率。网络连通性很高,所以我想为每个节点修剪边缘,只保留概率最高的节点。
我不确定如何遍历每个节点并只保留图中权重最高的 in_edges
。是否有一个 networkx 函数允许我们这样做?
这是我希望能够执行的操作的示例。
Nodes:
A, B, C, D
Edges:
A->B, weight=1.0
A->C, weight=1.0
A->D, weight=0.5
B->C, weight=0.9
B->D, weight=0.8
C->D, weight=0.9
Final Result Wanted:
A->B, weight=1.0
A->C, weight=1.0
C->D, weight=0.9
如果一个节点有两条边,并且它们的权重都最高,我想保留它们。
最佳答案
这里有一些想法:
import networkx as nx
G = nx.DiGraph()
G.add_edge('A','B', weight=1.0)
G.add_edge('A','C', weight=1.0)
G.add_edge('A','D', weight=0.5)
G.add_edge('B','C', weight=0.9)
G.add_edge('B','D', weight=0.8)
G.add_edge('C','D', weight=0.9)
print "all edges"
print G.edges(data=True)
print "edges >= 0.9"
print [(u,v,d) for (u,v,d) in G.edges(data=True) if d['weight'] >= 0.9]
print "sorted by weight"
print sorted(G.edges(data=True), key=lambda (source,target,data): data['weight'])
关于python - 查找给定节点的最高权重边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18218931/