Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding indices given condition in numpy matrix

Tags:

python

numpy

So I have a numpy matrix, such as:

[[1,2,3],
[0,59,2],
[54,4,2]]

Now I want to find the indices, where all values are greater than 50 (not the maximum). This should give me [1,1],[2,0].

Other than iterating through, checking each value and keeping track of indices for values which obey condition and then returning these pairs - how do you do this efficiently?

like image 241
redrubia Avatar asked Feb 19 '14 23:02

redrubia


People also ask

How do you find the index of list elements that meet a condition in python?

Use a list comprehension. Use enumerate() to create a list of (index, value) tuples from the input list a_list . Use a list comprehension on this list of tuples to select every index that corresponds to a value that meets the given condition, and return the selections as a list.


1 Answers

You want to use either numpy.where or numpy.argwhere:

import numpy as np
A = np.array([[99, 2, 3],
              [0, 59, 2],
              [54, 4, 2]])
np.where(A > 50)
# (array([0, 1, 2]), array([0, 1, 0]))
np.argwhere(A > 50)
# array([[0, 0],
#        [1, 1],
#        [2, 0]])
like image 77
Bi Rico Avatar answered Nov 15 '22 08:11

Bi Rico