查找图中所有不存在的连接
Find all inexistent connections in graph
我有一个 pandas 数据框 Edges 有两列 Node 1 |
节点 2
Node1 Node2
0 A B
1 C B
2 C D
这些基本上显示了边缘 (A,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)
我有一个 pandas 数据框 Edges 有两列 Node 1 | 节点 2
Node1 Node2
0 A B
1 C B
2 C D
这些基本上显示了边缘 (A,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)