How to access sparse matrix elements?

前端 未结 4 1831
情歌与酒
情歌与酒 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:32

    A[1,:] is itself a sparse matrix with shape (1, 60877). This is what you are printing, and it has only one row, so all the row coordinates are 0.

    For example:

    In [41]: a = csc_matrix([[1, 0, 0, 0], [0, 0, 10, 11], [0, 0, 0, 99]])
    
    In [42]: a.todense()
    Out[42]: 
    matrix([[ 1,  0,  0,  0],
            [ 0,  0, 10, 11],
            [ 0,  0,  0, 99]], dtype=int64)
    
    In [43]: print(a[1, :])
      (0, 2)    10
      (0, 3)    11
    
    In [44]: print(a)
      (0, 0)    1
      (1, 2)    10
      (1, 3)    11
      (2, 3)    99
    
    In [45]: print(a[1, :].toarray())
    [[ 0  0 10 11]]
    

    You can select columns, but if there are no nonzero elements in the column, nothing is displayed when it is output with print:

    In [46]: a[:, 3].toarray()
    Out[46]: 
    array([[ 0],
           [11],
           [99]])
    
    In [47]: print(a[:,3])
      (1, 0)    11
      (2, 0)    99
    
    In [48]: a[:, 1].toarray()
    Out[48]: 
    array([[0],
           [0],
           [0]])
    
    In [49]: print(a[:, 1])
    
    
    In [50]:
    

    The last print call shows no output because the column a[:, 1] has no nonzero elements.

提交回复
热议问题