Finding the maximum value and their indices in sparse lil_matrix (Scipy / Python)

What is the best way to find the maximum value and their corresponding row and column indices in a Scipy sparse lil_matrix object? I can scroll through non-zero entries using itertools.izip , but is there anything better? I feel like I'm missing something obvious here.

+4
source share
1 answer

You can convert to COO format and then use attributes data, rowand col.

For example, suppose the matrix is ​​LIL x. Here is one way to get the maximum value along with its row and column:

In [41]: x
Out[41]: 
<1000x1000 sparse matrix of type '<type 'numpy.float64'>'
    with 1999 stored elements in LInked List format>

In [42]: y = x.tocoo()

In [43]: k = y.data.argmax()

In [44]: maxval = y.data[k]

In [45]: maxrow = y.row[k]

In [46]: maxcol = y.col[k]

Note. There are two errors in the above code:

  • If all non-zero values ​​are negative, it will find the largest negative value. But the correct answer should be 0 in this case.
  • If there are no nonzero values, then the string k = y.data.argmax()will throw an exception because it y.datais an empty array.

If these cases cannot occur in your application, these errors can be ignored.

+6
source

All Articles