How to access sparse matrix elements?

前端 未结 4 1835
情歌与酒
情歌与酒 2021-01-31 02:07
type(A)

A.shape
(8529, 60877)
print A[0,:]
  (0, 25)   1.0
  (0, 7422) 1.0
  (0, 26062)    1.0
  (0, 31804)    1.0
  (0, 41         


        
4条回答
  •  轮回少年
    2021-01-31 02:36

    To answer your title's question using a different technique than your question's details:

    csc_matrix gives you the method .nonzero().

    Given:

    >>> import numpy as np
    >>> from scipy.sparse.csc import csc_matrix
    >>> 
    >>> row = np.array( [0, 1, 3])
    >>> col = np.array( [0, 2, 3])
    >>> data = np.array([1, 4, 16])
    >>> A = csc_matrix((data, (row, col)), shape=(4, 4))
    

    You can access the indices poniting to non-zero data by:

    >>> rows, cols = A.nonzero()
    >>> rows
    array([0, 1, 3], dtype=int32)
    >>> cols
    array([0, 2, 3], dtype=int32)
    

    Which you can then use to access your data, without ever needing to make a dense version of your sparse matrix:

    >>> [((i, j), A[i,j]) for i, j in zip(*A.nonzero())]
    [((0, 0), 1), ((1, 2), 4), ((3, 3), 16)]
    

提交回复
热议问题