I have an numpy array of dtype = object containing multiple other arrays for elements and I need to convert it to a sparse matrix.
Ex:
a = np.array([np.array([1,0,2]),np.array([1,3])])
array([array([1, 0, 2]), array([1, 3])], dtype=object)
I have tried the solution given by Convert numpy object array to sparse matrix with no success.
In [45]: M=sparse.coo_matrix(a)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-45-d75020bb3a38> in <module>()
----> 1 M=sparse.coo_matrix(a)
/home/arturcastiel/.local/lib/python3.6/site-packages/scipy/sparse/coo.py in __init__(self, arg1, shape, dtype, copy)
183 self._shape = check_shape(M.shape)
184
--> 185 self.row, self.col = M.nonzero()
186 self.data = M[self.row, self.col]
187 self.has_canonical_format = True
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
As it was explained on the comments, this is actually a jagged array. In essence, this array represents a graph that I have to convert to sparse matrix so I can use the scipy.sparse.csgraph.shortest_path routine.
Thus,
np.array([np.array([1,0,2]),np.array([1,3])])
should become something such as:
(1,1) 1
(1,2) 0
(1,3) 2
(2,1) 1
(2,2) 3