python - 查找给定节点的最高权重边

标签 python python-2.7 networkx

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

相关文章:

python - Pandas:根据值将包含分号的列分隔为多列

python - k-means 集群中的项数

python - Pandas 以最高值(value)保持复制

python - 将非方形邻接矩阵导入Networkx python

python - 可视化使用 pandas 数据框创建的二分网络图

python - 尝试访问 sdk 数据存储管理时出现导入错误

python-2.7 - 高斯NB :- ValueError: The sum of the priors should be 1

python - 在Python中从SPSS访问标签时如何处理特殊字符?

Networkx 图删除了计算级别顺序的冗余路径

python - 在 Pandas 的 DF 中间添加级别