How to find indices where values are true in a boolean matrix with numpy in python ?

Published: February 23, 2021

Tags: Python; Numpy;

DMCA.com Protection Status

Example of how to find indices where values are true in a boolean matrix with numpy in python:

Create a boolean matrix with numpy

Let's first create a random boolean matrix with False and True values

import numpy as np

A = np.full((5, 5), False)

n = 6

index = np.random.choice(A.size, n, replace=False)

A.ravel()[index] = True

print(A)

returns for example

[[False False False False False]
 [False  True False False False]
 [False  True  True False False]
 [ True False False False False]
 [False  True False False  True]]

Find indexes where values are true

To find indices where values are true, a solution is to use the numpy function where:

A_true = np.where( A )

print( A_true )

returns

(array([1, 2, 2, 3, 4, 4]), array([1, 1, 2, 0, 1, 4]))

Create a loop

for i in range(A_true[0].shape[0]):
    print('i = {}, j = {}'.format(A_true[0][i],A_true[1][i]))

returns

i = 1, j = 1
i = 2, j = 1
i = 2, j = 2
i = 3, j = 0
i = 4, j = 1
i = 4, j = 4

References