How to access sparse matrix elements?

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

    I fully acknowledge all the other given answers. This is simply a different approach.

    To demonstrate this example I am creating a new sparse matrix:

    from scipy.sparse.csc import csc_matrix
    a = csc_matrix([[1, 0, 0, 0], [0, 0, 10, 11], [0, 0, 0, 99]])
    print(a)
    

    Output:

    (0, 0)  1
    (1, 2)  10
    (1, 3)  11
    (2, 3)  99
    

    To access this easily, like the way we access a list, I converted it into a list.

    temp_list = []
    for i in a:
        temp_list.append(list(i.A[0]))
    
    print(temp_list)
    

    Output:

    [[1, 0, 0, 0], [0, 0, 10, 11], [0, 0, 0, 99]]
    

    This might look stupid, since I am creating a sparse matrix and converting it back, but there are some functions like TfidfVectorizer and others that return a sparse matrix as output and handling them can be tricky. This is one way to extract data out of a sparse matrix.

提交回复
热议问题