7

Given an arbitrary numpy array (ndarray), is there a function or a short way to convert it to a scipy.sparse matrix?

I'd like something that works like:

A = numpy.array([0,1,0],[0,0,0],[1,0,0])
S = to_sparse(A, type="csr_matrix")

3 Answers 3

9

I usually do something like

>>> import numpy, scipy.sparse
>>> A = numpy.array([[0,1,0],[0,0,0],[1,0,0]])
>>> Asp = scipy.sparse.csr_matrix(A)
>>> Asp
<3x3 sparse matrix of type '<type 'numpy.int64'>'
    with 2 stored elements in Compressed Sparse Row format>
Sign up to request clarification or add additional context in comments.

1 Comment

Hm, that was easy, I should have tried that. I didn't expect the constructor to do the conversion. This works for the constructors of the other sparse matrix types, too.
4

A very useful and pertinent example is in the help!

import scipy.sparse as sp
help(sp)

This gives:

Example 2
---------

Construct a matrix in COO format:

>>> from scipy import sparse
>>> from numpy import array
>>> I = array([0,3,1,0])
>>> J = array([0,3,1,2])
>>> V = array([4,5,7,9])
>>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4))

It's also worth noting the various constructors are (again from the help):

    1. csc_matrix: Compressed Sparse Column format
    2. csr_matrix: Compressed Sparse Row format
    3. bsr_matrix: Block Sparse Row format
    4. lil_matrix: List of Lists format
    5. dok_matrix: Dictionary of Keys format
    6. coo_matrix: COOrdinate format (aka IJV, triplet format)
    7. dia_matrix: DIAgonal format

To construct a matrix efficiently, use either lil_matrix (recommended) or
dok_matrix. The lil_matrix class supports basic slicing and fancy
indexing with a similar syntax to NumPy arrays.  

Your example would be as simple as:

S = sp.csr_matrix(A)

2 Comments

@clstaudt I'm not sure what you are looking for, sp.csr_matrix(A) would construct a csr type matrix from a dense numpy array A, while sp.csc_matrix(A) would construct a type csc matrix, etc... The constructors are the efficient conversion functions you are looking for (though read the caveats in the help).
You're right, the constructors do the conversions I was looking for. I expected them to take only arguments that correspond to the way entries are stored, like: A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
0

Please refer to this answer: https://stackoverflow.com/a/65017153/9979257

In this answer, I have explained how to convert a 2-dimensional NumPy matrix into CSR or CSC format.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.