python - 稀疏矩阵 : how to get nonzero indices for each row

标签 python numpy scipy sparse-matrix csr

我有一个 scipy CSR 矩阵,我想获取每一行的元素列索引。我的做法是:

import scipy.sparse as sp
N = 100
d = 0.1
M = sp.rand(N, N, d, format='csr')

indM = [row.nonzero()[1] for row in M]

indM 是我需要的,它的行数与 M 相同,看起来像这样:

[array([ 6,  7, 11, ..., 79, 85, 86]),
 array([12, 20, 25, ..., 84, 93, 95]),
...
 array([ 7, 24, 32, 40, 50, 51, 57, 71, 74, 96]),
 array([ 1,  4,  9, ..., 71, 95, 96])]

问题是对于大矩阵,这种方法看起来很慢。 有什么方法可以避免列表理解或以某种方式加快它的速度吗?

谢谢。

最佳答案

您可以直接使用 indicesindptr 属性:

import numpy
import scipy.sparse

N = 5
d = 0.3
M = scipy.sparse.rand(N, N, d, format='csr')
M.toarray()
# array([[ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
#        [ 0.        ,  0.        ,  0.        ,  0.        ,  0.30404632],
#        [ 0.63503713,  0.        ,  0.        ,  0.        ,  0.        ],
#        [ 0.68865311,  0.81492098,  0.        ,  0.        ,  0.        ],
#        [ 0.08984168,  0.87730292,  0.        ,  0.        ,  0.18609702]])

M.indices
# array([1, 2, 4, 3, 0, 1, 4], dtype=int32)
M.indptr
# array([0, 3, 4, 6, 6, 7], dtype=int32)

numpy.split(M.indices, M.indptr)[1:-1]
# [array([], dtype=int32),
#  array([4], dtype=int32),
#  array([0], dtype=int32),
#  array([0, 1], dtype=int32),
#  array([0, 1, 4], dtype=int32)]

关于python - 稀疏矩阵 : how to get nonzero indices for each row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44536107/

相关文章:

numpy - 以高值为中心的对数正态随机数

python - 类型错误 :ndarray not callable in scipy. stats.kstest()

python - 我想停止 python 中的平方函数线程,但它不起作用?

python - Matplotlibrc 需要更新吗?

python - 为什么 Tkinter 会破坏使用 canvas.create_image?

python - 将 Pandas 数据框中的所有列相乘

python Pandas : Getting the locations of a value in dataframe

python - 如何将 C 函数编译成 numpy ufunc 并动态加载它?

c++ - 通过 pybind11 从 C++ 使用 scipy

numpy - 在 NumPy 中按类别划分训练数据