What's the best way to find the maximum value and their corresponding row and column indices in a Scipy sparse lil_matrix object ? I can loop through the nonzero entries using itertools.izip, but is there anything better ? I feel like I'm missing something obvious here ..
Asked
Active
Viewed 2,911 times
1 Answers
6
You could convert to COO format, and then use the data
, row
and col
attributes.
For example, suppose the LIL matrix is x
. Here's 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 bugs in the above code:
- If all the nonzero values are negative, it will find the largest negative value. But the correct answer should be 0 in that case.
- If there are no nonzero values, then the line
k = y.data.argmax()
will raise an exception, becausey.data
is an empty array.
If those cases can't happen in your application, then those bugs can be ignored.

Warren Weckesser
- 110,654
- 19
- 194
- 214
-
1That saved me a lot of time. Thanks! – mab Sep 21 '15 at 08:10