Skip to content

Commit 55a2c94

Browse files
committed
improve from_networkx performance
1 parent 1c87aa9 commit 55a2c94

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

src/igraph/__init__.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1920,6 +1920,7 @@ def from_networkx(cls, g):
19201920
@param g: networkx Graph or DiGraph
19211921
"""
19221922
import networkx as nx
1923+
from collections import defaultdict
19231924

19241925
# Graph attributes
19251926
gattr = dict(g.graph)
@@ -1942,13 +1943,15 @@ def from_networkx(cls, g):
19421943
graph.vs[vd[v]][key] = val
19431944

19441945
# Edges and edge attributes
1945-
# NOTE: we need to do both together to deal well with multigraphs
1946-
# Each e might have a length of 2 (graphs) or 3 (multigraphs, the
1947-
# third element is the "color" of the edge)
1948-
for e, (_, _, datum) in zip(g.edges, g.edges.data()):
1949-
eid = graph.add_edge(vd[e[0]], vd[e[1]])
1950-
for key, val in list(datum.items()):
1951-
eid[key] = val
1946+
eattr_names = {name for (_, _, data) in g.edges.data() for name in data}
1947+
eattr = defaultdict(list)
1948+
edges = []
1949+
for (u, v, data) in g.edges.data():
1950+
edges.append((u,v))
1951+
for name in eattr_names:
1952+
eattr[name].append(data.get(name))
1953+
1954+
graph.add_edges(edges, eattr)
19521955

19531956
return graph
19541957

0 commit comments

Comments
 (0)