【发布时间】:2019-04-27 01:06:02
【问题描述】:
我有一个 dtype = object 的 numpy 数组,其中包含多个其他元素数组,我需要将其转换为稀疏矩阵。
例如:
a = np.array([np.array([1,0,2]),np.array([1,3])])
array([array([1, 0, 2]), array([1, 3])], dtype=object)
我尝试了Convert numpy object array to sparse matrix给出的解决方案,没有成功。
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()
正如在 cmets 上所解释的,这实际上是一个锯齿状数组。 本质上,这个数组表示一个图,我必须将其转换为稀疏矩阵,以便我可以使用 scipy.sparse.csgraph.shortest_path 例程。
因此,
np.array([np.array([1,0,2]),np.array([1,3])])
应该变成这样的:
(1,1) 1
(1,2) 0
(1,3) 2
(2,1) 1
(2,2) 3
【问题讨论】:
-
最终矩阵的形状应该是什么?第二个数组的数字
1, 3应该有什么坐标? -
你有一个参差不齐的数组,很多方法都不能满足这个要求