ndarray 与 scipy.sparse.csr.csr_matrix 的互转

版权声明:欢迎转载!如果不喜欢请留言说明原因再踩!谢谢,我也可以知道原因,不断进步!! https://blog.csdn.net/Scythe666/article/details/84623786

ndarry 转 csr_matrix

>>> import numpy as np
>>> import scipy.sparse

>>> my_matrix = scipy.sparse.csr_matrix((2,2))
>>> my_array = my_matrix.A
>>> type(my_array)
numpy.ndarray

csr_matrix 转 ndarray

>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])

>>> A
array([[1, 2, 0],
       [0, 0, 3],
       [1, 0, 4]])

>>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.

>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>

>>> print sA
  (0, 0)        1
  (0, 1)        2
  (1, 2)        3
  (2, 0)        1
  (2, 2)        4

猜你喜欢

转载自blog.csdn.net/Scythe666/article/details/84623786