简体   繁体   中英

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

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 ..

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, because y.data is an empty array.

If those cases can't happen in your application, then those bugs can be ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM