使用numpy.NaN初始化scipy.sparse矩阵的最快方法是什么?

时间:2013-01-17 08:23:16

标签: python scipy

我想用numpy数组初始化一个稀疏矩阵。 numpy数组包含我的程序的NaN为零,初始化稀疏矩阵的代码如下:

a= np.array([[np.NaN,np.NaN,10]])
zero_a= np.array([[0,0,10]])
spr_a = lil_matrix(a)
zero_spr_a = lil_matrix(zero_a)
print repr(spr_a)
print repr(zero_spr_a)

输出

1x3 sparse matrix of type 'type 'numpy.float64''
    with 3 stored elements in LInked List format
1x3 sparse matrix of type 'type 'numpy.int64''
    with 1 stored elements in LInked List format

对于带0的数组,只有1个元素存储在稀疏矩阵中。但是NaN数组中存储了3个元素,如何将NaN视为零作为scipy矩阵?

2 个答案:

答案 0 :(得分:5)

如果您只想从数据中创建稀疏矩阵,将NaN视为零,则可以执行以下操作。首先,让我们创建一个包含多个np.nan的随机数组:

>>> nans = np.random.randint(0, 2, size=(5,5))
>>> a = np.ones((5,5))
>>> a = np.where(nans, np.nan, a)
>>> a
array([[  1.,   1.,   1.,   1.,  nan],
       [ nan,  nan,  nan,   1.,   1.],
       [ nan,  nan,   1.,   1.,  nan],
       [  1.,   1.,   1.,   1.,  nan],
       [  1.,  nan,   1.,  nan,  nan]])

要使COO格式稀疏,它就像:

一样简单
>>> indices = np.nonzero(~np.isnan(a))
>>> sps = scipy.sparse.coo_matrix((a[indices], indices), shape=a.shape)
>>> sps
<5x5 sparse matrix of type '<type 'numpy.float64'>'
    with 14 stored elements in COOrdinate format>

并检查它们是否相同:

>>> sps.toarray()
array([[ 1.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  1.,  1.],
       [ 0.,  0.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  0.],
       [ 1.,  0.,  1.,  0.,  0.]])

虽然您的NaN现已消失......

答案 1 :(得分:2)

在稀疏矩阵中使用零作为空值在代码中根深蒂固,所以不幸的是它不容易改变。

首先,我会重新考虑是否需要将NaN或其他值视为稀疏矩阵中的空值。也许你的代码中有另一种方式?

如果你真的必须更改稀疏矩阵中的空值,那么你必须根据lil_matrix甚至spmatrix来定义一个新类。最重要的是,您需要更改方法get nnz(),该方法定义了多少点非零。但是你还需要重新定义矩阵,因为它被转换为对象dtype的np.matrix,并且在此过程中清零。