0

I have a networkx graph containing a bunch of nodes whose names are string arrays; specifically, the following:

>>> g.nodes()
['[0. 1. 2. 4.]', '[0. 1. 2. 5.]', '[0. 1. 4. 2.]', '[0. 1. 5. 2.]', '[0. 2. 1. 4.]', '[0. 2. 1. 5.]', '[0. 2. 2. 4.]', '[0. 2. 2. 5.]', '[0. 2. 4. 1.]', '[0. 2. 4. 2.]', '[0. 2. 5. 1.]', '[0. 2. 5. 2.]', '[0. 4. 1. 2.]', '[0. 4. 2. 1.]', '[0. 4. 2. 2.]', '[0. 5. 1. 2.]', '[0. 5. 2. 1.]', '[0. 5. 2. 2.]', '[1. 2. 0. 4.]', '[1. 2. 0. 5.]', '[1. 2. 2. 4.]', '[1. 2. 2. 5.]', '[1. 2. 4. 0.]', '[1. 2. 4. 2.]', '[1. 2. 5. 0.]', '[1. 2. 5. 2.]', '[1. 4. 0. 2.]', '[1. 4. 2. 0.]', '[1. 4. 2. 2.]', '[1. 5. 0. 2.]', '[1. 5. 2. 0.]', '[2. 0. 1. 4.]', '[2. 0. 1. 5.]', '[2. 0. 2. 4.]', '[2. 0. 2. 5.]', '[2. 0. 4. 1.]', '[2. 0. 4. 2.]', '[2. 0. 5. 1.]', '[2. 0. 5. 2.]', '[2. 1. 0. 4.]', '[2. 1. 0. 5.]', '[2. 1. 2. 4.]', '[2. 1. 2. 5.]', '[2. 1. 4. 0.]', '[2. 1. 4. 2.]', '[2. 1. 5. 0.]', '[2. 1. 5. 2.]', '[2. 2. 0. 4.]', '[2. 2. 0. 5.]', '[2. 2. 1. 4.]', '[2. 2. 1. 5.]', '[2. 2. 4. 0.]', '[2. 2. 4. 1.]', '[2. 2. 5. 0.]', '[2. 2. 5. 1.]', '[2. 4. 0. 1.]', '[2. 4. 0. 2.]', '[2. 4. 1. 0.]', '[2. 4. 1. 2.]', '[2. 4. 2. 0.]', '[2. 4. 2. 1.]', '[2. 5. 0. 1.]', '[2. 5. 0. 2.]', '[2. 5. 1. 0.]', '[2. 5. 1. 2.]', '[2. 5. 2. 0.]', '[2. 5. 2. 1.]', '[4. 0. 1. 2.]', '[4. 0. 2. 1.]', '[4. 0. 2. 2.]', '[4. 1. 0. 2.]', '[4. 1. 2. 0.]', '[4. 1. 2. 2.]', '[4. 2. 0. 1.]', '[4. 2. 0. 2.]', '[4. 2. 1. 0.]', '[4. 2. 1. 2.]', '[4. 2. 2. 0.]', '[4. 2. 2. 1.]', '[5. 0. 1. 2.]', '[5. 0. 2. 1.]', '[5. 1. 0. 2.]', '[5. 1. 2. 0.]', '[5. 1. 2. 2.]', '[5. 2. 0. 1.]', '[5. 2. 0. 2.]', '[5. 2. 1. 0.]', '[5. 2. 1. 2.]', '[5. 2. 2. 0.]', '[5. 2. 2. 1.]']

I would then like to visualize this graph using pyvis. I try the following code:

net = Network()
net.from_nx(g)
net.show("rb_graph.html")

which gives me the error TypeError: Object of type ndarray is not JSON serializable on the third line. This is weird, because the node names are strings, and not numpy.ndarrays. Just in case, I tried converting them to strings anyways:

h = g.copy()
h = nx.relabel_nodes(h, lambda x: str(x) )
net = Network()
net.from_nx(h)
net.show("rb_graph.html")

But this gives the same error.

Indeed, if I run

for n in h.nodes():
    print(type(n))

I get <class 'str'> 90 times.

What is causing this strange behaviour?

==Edit==

For whatever reason, the following code works:

h = g.copy()
h = nx.relabel_nodes(h, lambda x: str(x))
net = Network()
net.from_nx(h)
j = h.copy()
net = Network()
net.show("rb_graph.html")
net.from_nx(j)
net.show("rb_graph.html")

I'm using this for now, but I feel like I'm going crazy.

416E64726577
  • 2,214
  • 2
  • 23
  • 47
  • Could you provide the code to generate your network or a minimal example of a network that reproduces your error? – jylls Jan 23 '23 at 18:34

0 Answers0