SciPy 稀疏数组:获取数据点的索引

SciPy Sparse Array: Get index for a data point

我正在创建一个 csr 稀疏数组(因为我有很多空 elements/cells),我需要向前和向后使用。也就是说,我需要输入两个索引并获取与其对应的元素(矩阵[0][9]=34),但我还需要能够在知道值为 34 时获取索引。元素在我的阵列都是独一无二的。我已经到处寻找关于这个的答案,但还没有找到,或者可能不明白这就是我正在寻找的东西!我是 python 的新手,所以如果您能确保让我知道您找到的函数的作用以及检索元素索引的步骤,我将不胜感激!

提前致谢!

您可以使用nonzero方法:

In [44]: from scipy.sparse import csr_matrix

In [45]: a = np.arange(50).reshape(5, 10)

In [46]: a
Out[46]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

In [47]: s = csr_matrix(a)

In [48]: s
Out[48]: 
<5x10 sparse matrix of type '<type 'numpy.int64'>'
    with 49 stored elements in Compressed Sparse Row format>

In [49]: (s == 36).nonzero()
Out[49]: (array([3], dtype=int32), array([6], dtype=int32))

一般来说,尝试一种适用于 numpy 数组的方法通常会奏效。这并不总是奏效,但至少在这里它奏效了(我今天学到了一些新东西)。

这是一种查找适用于 numpy 数组和稀疏矩阵的特定值的方法

In [119]: A=sparse.csr_matrix(np.arange(12).reshape(3,4))

In [120]: A==10
Out[120]: 
<3x4 sparse matrix of type '<class 'numpy.bool_'>'
    with 1 stored elements in Compressed Sparse Row format>

In [121]: (A==10).nonzero()
Out[121]: (array([2], dtype=int32), array([2], dtype=int32))

In [122]: (A.A==10).nonzero()
Out[122]: (array([2], dtype=int32), array([2], dtype=int32))