python - 查找图中所有不存在的连接

标签 python pandas networkx graph-theory

我有一个 Pandas 数据框 边缘 两列节点 1 |
节点 2

      Node1     Node2
 0      A         B
 1      C         B
 2      C         D

这些基本上显示边缘 (A,B) | (C,B) | (C,D) 在图表中

我需要找出的是缺失边缘,即不存在 (A,D) | (B,D) | (A,C)

期望输出
      Node1     Node2
 0      A         D
 1      A         C
 2      B         D

我试过的:

我将 DataFrame 转换为 networkx 图,然后出于相同目的使用 nx.non_edges 函数(查找缺失的边)
但是由于硬件资源不足,networkx 会填满 RAM 并且笔记本电脑崩溃。
我正在尝试通过 Pandas Dataframe 查找是否有可能丢失图形的边缘,或者您可以说我需要找到图形的补充。

最佳答案

一种可能的方法如下:

  • 查找所有长度 2节点组合
  • 迭代它们
  • 保留 G.edges 中未包含的组合

  • from itertools import combinations
    
    G = nx.from_pandas_edgelist(df, source='Node1', target='Node2')
    
    edge_non_present = []
    edges = set(G.edges())
    for possible_edge in combinations(G.nodes(), r=2):
        if possible_edge not in edges:
            edge_non_present.append(possible_edge)
    
    print(edge_non_present)
    # [('A', 'C'), ('A', 'D'), ('B', 'D')]
    

    更新

    如果由于大量节点而导致大量组合,请获取返回的生成器的一部分,并仅迭代其中的一个子集:
    from itertools import islice
    
    G = nx.from_pandas_edgelist(df, source='Node1', target='Node2')
    n_comb = 100
    
    edge_non_present = []
    edges = set(G.edges())
    for possible_edge in islice(combinations(G.nodes(), r=2), 0, n_comb):
        if possible_edge not in edges:
            edge_non_present.append(possible_edge)
    

    关于python - 查找图中所有不存在的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186215/

    相关文章:

    python - 如何在单个操作中展平具有已知分隔符的列表列表

    使用包含带有 span 元素的文本时的 Python selenium 问题

    Python 自身类型错误 : add_state() takes exactly 4 arguments (3 given)

    python - Pandas 有条件 True

    python - 查找有向图中的所有前驱节点

    Python for循环查询

    python - KeyError : 'url_encoded_fmt_stream_map'

    python Pandas : find the element that is a string in a pandas DataFrame

    python - 如何将节点放置在特定位置 - networkx

    python - 在 NetworkX 中绘制图形