Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert list and list of lists to scipy sparse arrays

Suppose I have a list or a list of lists (each list with the same size). How do I convert to a sparse vector or sparse matrix, respectively?

like image 285
Bob Avatar asked Jul 24 '14 04:07

Bob


People also ask

What is SciPy sparse in Python?

Sparse data is data that has mostly unused elements (elements that don't carry any information ). It can be an array like this one: [1, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0] Sparse Data: is a data set where most of the item values are zero.

What is the SciPy function which creates a sparse matrix?

from scipy.sparse import csc_matrix. # Creating a 3 * 4 sparse matrix. sparseMatrix = csc_matrix(( 3 , 4 ), dtype = np.int8).toarray() # Print the sparse matrix.

What is Lil_matrix?

lil_matrix((M, N), [dtype]) to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype='d'. Notes. Sparse matrices can be used in arithmetic operations: they support addition, subtraction, multiplication, division, and matrix power.


1 Answers

In [5]: scipy.sparse.csr_matrix([[1, 2], [3, 0]])
Out[5]:
<2x2 sparse matrix of type '<type 'numpy.int64'>'
        with 3 stored elements in Compressed Sparse Row format>

In [6]: scipy.sparse.csr_matrix([1, 2])
Out[6]:
<1x2 sparse matrix of type '<type 'numpy.int64'>'
        with 2 stored elements in Compressed Sparse Row format>

scipy.sparse.whatever_matrix_type(your_data_structure). It's quite analogous to what you'd do to get a regular array. Note that there is no sparse vector or sparse ndarray class, only sparse matrices.

like image 164
user2357112 supports Monica Avatar answered Sep 28 '22 07:09

user2357112 supports Monica