【问题标题】:Efficient extraction of a subgraph according to some edge attribute in NetworkX根据 NetworkX 中的某些边缘属性有效提取子图
【发布时间】:2025-12-25 13:05:16
【问题描述】:

可以通过指定节点列表轻松地从 NetworkX 图中提取子图,但我找不到按边执行子图提取的有效方法。例如,要提取由权重超过某个用户定义阈值的边组成的子图。

目前我正在通过以下方式进行操作:

## extracts all edges satisfy the weight threshold (my_network is directed):
eligible_edges = [(from_node,to_node,edge_attributes) for from_node,to_node,edge_attributes in my_network.edges(data=True) if edge_attributes['weight'] > threshold]
new_network = NetworkX.DiGraph()
new_network.add_edges_from(eligible_edges)

有没有更好的方法来做到这一点?

感谢您的友好回答。

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    这看起来是最好的解决方案。

    你可以使用graph.edges_iter()而不是graph.edges()来节省内存,例如

    >>> G = nx.DiGraph(((source, target, attr) for source, target, attr in my_network.edges_iter(data=True) if attr['weight'] > threshold))
    

    【讨论】:

    • 作为未来我们这些人的仅供参考,从 networkx 2.0+ 开始,edges 提供了一个可以迭代的特殊视图对象,因此 edges_iter() 现在已被删除,我们将回edges();更多信息:networkx.github.io/documentation/stable/release/…