Reputation: 127
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 ..
Upvotes: 4
Views: 3077
Reputation: 114781
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:
k = y.data.argmax()
will raise an exception, because y.data
is an empty array.If those cases can't happen in your application, then those bugs can be ignored.
Upvotes: 7