3

I got an issue when trying to cast a networkx graph list into a Numpy array. It appears that when all graphs of the list have the same number of nodes, Numpy automatically converts input graphs into arrays and the result is not what I expect.

Here is a small reproduction script:

import numpy as np
import networkx as nx

g1 = nx.DiGraph([(1, 2), (2, 3)])
g2 = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
g3 = nx.DiGraph([(1, 2), (2, 1), (1, 3)])

ok_numpy = np.array([g1, g2], dtype=object)
ko_numpy = np.array([g1, g3], dtype=object)

>> ok_numpy = [<networkx.classes.digraph.DiGraph object at ...>, <networkx.classes.digraph.DiGraph object at ...>]
>> ko_numpy = [[1 2 3], [1 2 3]] <-- Objects are not DiGraph() anymore, edges info is lost, dimension is 2 instead of 1

If anybody knows a solution so that ko_numpy could behave the same way ok_numpy does, it would be perfect.

1
  • Can't you leave it as a list? What benefit is there to making an array? Commented Jan 13, 2023 at 15:34

1 Answer 1

4

This is a bug-feature of numpy, see this answer. The current solution is to create an empty array and assign specific elements to it:

ko_numpy2 = np.empty(2, dtype=object)
ko_numpy2[:] = [g1, g3]

Not ideal, but workable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.