How to convert a ndarray to an igraph's graph quickly?

I have a ndarray which calls pairs looks like this:

you can see every elements in the ndarray is an array which length is 2.
Now I want to convert pairs to a list of tuples and add the list to an graph,but I can’t find a fast method to complete this.
I have used this code to convert:

for i in range(0, len(pairs)):
        pairs[i] = tuple(pairs[i])

but there is no any change in pairs ndarray, so how to change my code? Thanks for very much.

You can use numpy arrays directly. Graph(pairs) should work for creating a graph. If it does not, please show a complete minimal example, and include your numpy and igraph versions.

1 Like

This is my crash report: in build_graph

graph = <igraph.Graph object at 0x000002C86F83BC40>
es = array([[ 1, 4],
[ 1, 2],
[ 2, 4],
[77912, 77911],
[77912, 48205],
[77912, 48130]], dtype=int64)
attributes = None

def _add_edges(graph, es, attributes=None):
    """Adds some edges to the graph.

    @param es: the list of edges to be added. Every edge is represented
      with a tuple containing the vertex IDs or names of the two
      endpoints. Vertices are enumerated from zero.
    @param attributes: dict of sequences, all of length equal to the
      number of edges to be added, containing the attributes of the new
    eid = graph.ecount()
  res = GraphBase.add_edges(graph, es)
E       igraph._igraph.InternalError: Error at src/graph/type_indexededgelist.c:261: Out-of-range vertex IDs when adding edges. -- Invalid vertex ID

Oh,the method can pass the test:
total_graph = ig.Graph(pairs, directed=True)
But why add_edges fails?

This error will occur when you pass invalid vertex IDs to add_edges(). Valid IDs are between 0 and g.vcount() - 1 (inclusive).

If you want to create a graph from an edge list, do not use add_edges(). Use the Graph constructor instead, which will automatically determine the appropriate vertex count.

If there are further problems, please include a short but complete reproducer according to the guidelines here: How to create a Minimal, Reproducible Example - Help Center - Stack Overflow Be sure to mention your igraph version (ideally use the latest version).

Simple way to create graph from edge list:

In [4]: g1 = ig.Graph([(0,1), (1,2)])

You can also do this:

In [5]: g2 = ig.Graph()

This graph has no vertices:

In [6]: g2.vcount()
Out[6]: 0

Thus e.g. vertex ID 2 is not valid.

In [7]: g2.add_edges([(0,1), (1,2)])

InternalError: Error at src/graph/type_indexededgelist.c:261: Out-of-range vertex IDs when adding edges. -- Invalid vertex ID

You need to add at least 3 vertices in order for vertex ID 2 to be valid.

In [8]: g2.add_vertices(3)

In [9]: g2.add_edges([(0,1), (1,2)])