将 NetworkX 图转换为 igraph 的两种方法:
import networkx as nx, igraph as ig
# create sample NetworkX graph
g = nx.planted_partition_graph(5, 5, 0.9, 0.1, seed=3)
# convert via edge list
g1 = ig.Graph(len(g), list(zip(*list(zip(*nx.to_edgelist(g)))[:2])))
# nx.to_edgelist(g) returns [(0, 1, {}), (0, 2, {}), ...], which is turned
# into [(0, 1), (0, 2), ...] for igraph
# convert via adjacency matrix
g2 = ig.Graph.Adjacency((nx.to_numpy_matrix(g) > 0).tolist())
assert g1.get_adjacency() == g2.get_adjacency()
对于我的机器上的以下 2500 节点图,使用边列表稍微快一些:(请注意,下面的代码仅适用于 Python 2;我将上面的代码更新为与 Python 2/3 兼容。)
In [5]: g = nx.planted_partition_graph(50, 50, 0.9, 0.1, seed=3)
In [6]: %timeit ig.Graph(len(g), zip(*zip(*nx.to_edgelist(g))[:2]))
1 loops, best of 3: 264 ms per loop
In [7]: %timeit ig.Graph.Adjacency((nx.to_numpy_matrix(g) > 0).tolist())
1 loops, best of 3: 496 ms per loop
对于g = nx.complete_graph(2500),使用边缘列表也更快。