Skip to main content
 首页 » 编程设计

python之NetworkX 中的二分体在重命名节点时无法正常工作

2024年10月24日13jyk

我正在尝试使用 networkX 将二分图转换为人对人图:

import networkx as nx 
import ast 
from networkx.algorithms import bipartite 
x=(161,1),(589,2),(162,1),(163,1),(589,2) 
BI = nx.Graph() 
BI.add_edges_from(x) 
bottom_nodes, top_nodes = bipartite.sets(BI) 
GI = bipartite.projected_graph(BI, top_nodes) 
GI.edges() 

结果不正确:

>>> bottom_nodes 
{161, 162, 163, 2} 
>>> top_nodes 
{1, 589} 

如果我将 x 更改为:

x=(61,1),(58,2),(62,1),(63,1),(59,2) 

我得到正确的结果:

>>> bottom_nodes 
{1, 2} 
>>> top_nodes 
{58, 59, 61, 62, 63} 

所以不知何故,如果我对节点使用“较低”的数字,那么转换是正确的,否则不是。但是,我需要更大的数字,因为我有 100 多个节点。

请您参考如下方法:

因为您已经知道您的二分集是什么,您可以明确指定它们。

import networkx as nx                                                            
from networkx.algorithms import bipartite                                        
x=(161,1),(589,2),(162,1),(163,1),(589,2)                                        
BI = nx.Graph(x)                                                                 
top = set(s for s,t in x)                                                        
print(top)                                                                       
GI = bipartite.projected_graph(BI, top)                                          
print(list(GI.edges()))   

输出

set([161, 162, 163, 589]) 
[(161, 162), (161, 163), (162, 163)]