Home > Software engineering >  Retrieve indices of certain value in a matrix and put it in a nested list
Retrieve indices of certain value in a matrix and put it in a nested list

Time:12-22

I have this matrix; let's say there are hundreds of x value and thousands of y lists inside this matrix:

[[100   0   0 ...   0   0   0]
 [  0 100   0 ...   0   0   0]
 [  0   0 100 ...   0   0   0]
 ...
 [  0   0   0 ... 100   0   0]
 [  0   0   0 ...   0 100   0]
 [  0   0   0 ...   0   0 100]]

How will I be able to retrieve the index of value >= 90 and put it in a nested list?

Here is the sample output:

[[0], [1, 167], [2, 498, 2890] ... [6568, 99998], [7894, 19695, 99999], [873, 100000]]

CodePudding user response:

Try using nested list comprehension:

[[idx for idx, value in enumerate(row) if value >= 90] for row in arr]

To have the result of @azro's, I'd rather use:

np.argwhere(arr >= 90)

CodePudding user response:

The post numpy get index where value is true might help

numpy.transpose((array > value).nonzero())

import numpy as np

values = np.array([[1, 76, 987, 1, 1, 1], [876, 76, 765, 1, 1, 1], [1, 3, 4, 1, 1, 1],
                   [1, 3, 4, 1, 1, 1], [1, 3, 4, 1, 1, 1], [1, 3, 4, 1, 1, 123]])

result = np.transpose((values > 90).nonzero())
print(result)
[[0 2]
 [1 0]
 [1 2]
 [5 5]]
  • Related