NumPy: How to Get Indices Where Value is True


You can use the following methods to get the indices where some condition is true in NumPy:

Method 1: Get Indices Where Condition is True in NumPy Array

#get indices of values greater than 10
np.asarray(my_array>10).nonzero()

Method 2: Get Indices Where Condition is True in NumPy Matrix

#get indices of values greater than 10
np.transpose((my_matrix>10).nonzero())

Method 3: Get Indices Where Condition is True in Any Row of NumPy Matrix

#get indices of rows where any value is greater than 10
np.asarray(np.any(my_matrix>10, axis=1)).nonzero()

The following examples show how to use each method in practice.

Example 1: Get Indices Where Condition is True in NumPy Array

The following code shows how to get all indices in a NumPy array where the value is greater than 10:

import numpy as np

#create NumPy array
my_array = np.array([2, 2, 4, 5, 7, 9, 11, 12, 3, 19])

#get index of values greater than 10
np.asarray(my_array>10).nonzero()

(array([6, 7, 9], dtype=int32),)

From the output we can see that the values in index positions 6, 7, and 9 of the original NumPy array have values greater than 10.

Example 2: Get Indices Where Condition is True in NumPy Matrix

The following code shows how to get all indices in a NumPy matrix where the value is greater than 10:

import numpy as np

#create NumPy matrix
my_matrix = np.array([[2, 5, 9, 12],
                     [6, 7, 8, 8],
                     [2, 5, 7, 8],
                     [4, 1, 15, 11]])

#get index of values greater than 10
np.transpose((my_matrix>10).nonzero())

array([[0, 3],
       [3, 2],
       [3, 3]], dtype=int32)

From the output we can see that the values in the following index positions of the matrix have values greater than 10:

  • [0, 3]
  • [3, 2]
  • [3, 3]

Example 3: Get Indices Where Condition is True in Any Row of NumPy Matrix

The following code shows how to get all row indices in a NumPy matrix where the value is greater than 10 in any element of the row:

import numpy as np

#create NumPy matrix
my_matrix = np.array([[2, 5, 9, 12],
                     [6, 7, 8, 8],
                     [2, 5, 7, 8],
                     [4, 1, 15, 11]])

#get index of rows where any value is greater than 10
np.asarray(np.any(my_matrix>10, axis=1)).nonzero()

(array([0, 3], dtype=int32),)

From the output we can see that rows 0 and 3 have at least one value greater than 10.

Note: To get indices where a condition is true in a column, use axis=0 instead.

Additional Resources

The following tutorials explain how to perform other common tasks in NumPy:

How to Fill NumPy Array with Values
How to Remove Specific Elements from NumPy Array
How to Replace Elements in NumPy Array
How to Get Specific Row from NumPy Array

Leave a Reply

Your email address will not be published.