3

I want to convert a sparse matrice in list of non zero index like this :

>>> row = array([0,2,2,0,1,2])
>>> col = array([0,0,1,2,2,2])
>>> data = array([1,1,1,1,1,1])
>>> mat = csc_matrix( (data,(row,col)), shape=(3,3) )
>>> mat.todense() 
matrix([[1, 0, 1],
    [0, 0, 1],
    [1, 1, 1]])
>>> convert(mat)
[[0, 2],[2],[0, 1, 2]]
5
  • 2
    It's unclear to me how the output of convert relates to mat. Commented Mar 23, 2012 at 16:06
  • I'll state it more strongly: I have no idea how the output of convert relates to mat, or perhaps more importantly, to the input row/col/data. Commented Mar 23, 2012 at 16:09
  • a list of non zero index Commented Mar 23, 2012 at 16:12
  • Oh, right, you changed the third value of the output as well. Sorry, hadn't seen that. Commented Mar 23, 2012 at 16:14
  • @zedouard: Are you looking for the non-zero entries, or rather for the entries occurring in the sparsity pattern? Commented Mar 23, 2012 at 16:15

2 Answers 2

1

Maybe something like

>>> from numpy import array
>>> from scipy.sparse import csc_matrix
>>> 
>>> row = array([0,2,2,0,1,2])
>>> col = array([0,0,1,2,2,2])
>>> data = array([1,1,1,1,1,1])
>>> mat = csc_matrix( (data,(row,col)), shape=(3,3) )
>>> [list(line.nonzero()[1]) for line in mat]
[[0, 2], [2], [0, 1, 2]]

would help? You should probably look at nonzero, anyway.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, i'm looking for something like that, but i wonder if there isn't exist a function to do this
Maybe you can make do with the output of mat.nonzero()?
[list(mat[i].nonzero()[1]) for i in range(mat.shape[0])] "for line in mat" doesn't work
@zedouard: it should, unless there's an edge case I haven't thought of. In what way did it not work?
1

Maybe you are looking for something like this:

>>> [mat.indices[mat.indptr[i]:mat.indptr[i+1]]
     for i in range(len(mat.indptr) - 1)]
[array([0, 2]), array([2]), array([0, 1, 2])]

Not sure what this is supposed to be useful for, though. Chances are there are better ways of achieving what you are trying to do.

2 Comments

This is very CSC/CSR-format specific. @DSM's nonzero-based answer will work for all scipy.sparse types.
@larsmans: The important difference is that this answer gives the sparsity pattern, while DSM's answer gives the non-zero elements. I don't think there's a type-agnostic way to get the sparsity pattern. Also note that DSM's answer doesn't work for coo_matrix and dia_matrix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.