python - 删除边缘时如何保留路径 networkx 图

标签 python graph networkx

当我过滤 networkx 图中的特定节点时,我想保留路径。 让我们说我有下图。

enter image description here

当我删除节点 20 时,我想保留与下一个节点的路径或连接,因为存在通过节点 20 的连接。

我想要以下内容。

enter image description here

有人可以帮助我使用 Python 应对这一挑战吗?

最佳答案

对于有向图,您可以使用 g.in_edges(node) 获取节点的所有边,并使用 g.out_edges(node) 获取所有出边. 一旦有了这些,连接入射边的源和出射边的目标就很简单了。 无向图没有传入和传出边的概念,因此您只需组合邻居 (g.neighbors)。 最后,您删除您的节点。

enter image description here

#!/usr/bin/env python
"""
Remove a node from a network while maintaining all paths.
"""
import itertools
import matplotlib.pyplot as plt
import networkx as nx

def remove_node(g, node):
    if g.is_directed():
        sources = [source for source, _ in g.in_edges(node)]
        targets = [target for _, target in g.out_edges(node)]
    else:
        sources = g.neighbors(node)
        targets = g.neighbors(node)

    new_edges = itertools.product(sources, targets)
    new_edges = [(source, target) for source, target in new_edges if source != target] # remove self-loops
    g.add_edges_from(new_edges)

    g.remove_node(node)

    return g

if __name__ == '__main__':

    edges = [(10, 20), (20, 30), (30, 40)]
    g = nx.DiGraph()
    g.add_edges_from(edges)

    fig, (ax1, ax2) = plt.subplots(1, 2)
    nx.draw_networkx(g, with_labels=True, ax=ax1)

    g = remove_node(g, 20)

    nx.draw_networkx(g, with_labels=True, ax=ax2)
    plt.show()

关于python - 删除边缘时如何保留路径 networkx 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58799219/

相关文章:

Python argparse 切换标志

python - 迭代 CSV 列时出现 IndexError

python - 在 Spring 布局+网络中更改节点的颜色

python - 'Sequence of ParamSpec' 的类型提示

python - 从 PySpark 中的两个不同数据框中减去列的值以查找 RMSE

java - 使用 JFreeChart 的故障绘图

javascript - Cytoscape 中反射(reflect)重量的边缘

graph - 平行边缘检测

python - 3d 矩阵到 2d 邻接矩阵或边列表

python - pandas 字符串列的交集/子集