简体   繁体   中英

Accessing Single Entries in Sparse Matrix in Python

I want to use sparse matrices for BOW feature representation. I have experimented with coo_matrix from scipy, but it doesn't seem to support what I want to do:

I would like to initialize a matrix of all zeros and then change a given entry to one when appropriate. But when I try to index the matrix how I think I should -- myMatrix[0][0] = 1 (or even myMatrix[0][0][0] =1), for example -- it changes all the values in a row to 1. I want to just make a single entry 1.

I can do this easily with numpy matrices, but I would like to use sparse matrices for space efficiency.

Using the right sparse type helps.

from scipy import sparse
M = sparse.lil_matrix((10,10))
M[1,1] = 1
M[5,5] = 1
# <10x10 sparse matrix of type '<type 'numpy.float64'>'
#   with 2 stored elements in LInked List format>

dok also works. csr suggests using lil . 'coo' can't be set this way. Once filled it is easy to convert to another format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM