我有一个 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/