查找给定节点的最大权重边

2024-04-25 15:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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

如果一个节点中有两条边,并且它们都是最大的权重,我希望保留这两条边。


Tags: 函数in网络networkx节点概率事情边缘
2条回答

以下是一些想法:

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

我得到的解决办法是受阿里克的启发。我使用了以下代码:

for node in G.nodes():
    edges = G.in_edges(node, data=True)
    if len(edges) > 0: #some nodes have zero edges going into it
        min_weight = min([edge[2]['weight'] for edge in edges])
        for edge in edges:
            if edge[2]['weight'] > min_weight:
                G.remove_edge(edge[0], edge[1])

相关问题 更多 >