1

I have 2 numpy arrays. One is filled with boolean values and the other numerical values.

How would I perform logic on the numerical array based on also the current value in the boolean array.

e.g. if true and > 5 then make the value false

matrix1
matrix2

newMatrix = matrix1 > 5 where matrix2 value is false

Please note that these arrays have the same shape e.g.

[[0, 1, 1],  
[1, 0, 0]]

and

[[3, 1, 0]  
[6, 2, 6]]

And the result I would like would be a new boolean matrix that is true if its value is true in the boolean array and the equivalent value in the numerical array is more than 5 e.g.

[[0, 0, 0]  
[1, 0, 0]]
sentence
  • 8,213
  • 4
  • 31
  • 40
OultimoCoder
  • 244
  • 2
  • 7
  • 24

2 Answers2

1
newMatrix = np.logical_and(matrix2 == 0, matrix1 > 5 )

This will iterate over all elements, and make an 'and' between pairs of booleans from matrix == 0 and matrix1 > 5. Note that matrix1 > 5 type of expression generates a matrix of boolean values.

If you want 0,1 instead of False,True, you can add +0 to the result:

newMatrix = np.logical_and(matrix2 == 0, matrix1 > 5 ) + 0
Michael Veksler
  • 8,217
  • 1
  • 20
  • 33
0

The clearest way:

import numpy as np

matrix1 = np.array([[3, 1, 0],
                    [6, 2, 6]])

matrix2 = np.array([[0, 1, 1],
                    [1, 0, 0]])

r,c = matrix1.shape

res = np.zeros((r,c))

for i in range(r):
    for j in range(c):
        if matrix1[i,j]>5 and matrix2[i,j]==1:
            res[i,j]=1

result

array([[0., 0., 0.],
       [1., 0., 0.]])

A fancier way, using numpy.where():

import numpy as np

matrix1 = np.array([[3, 1, 0],
                    [6, 2, 6]])

matrix2 = np.array([[0, 1, 1],
                    [1, 0, 0]])

r,c = matrix1.shape

res = np.zeros((r,c))

res[np.where((matrix1>5) & (matrix2==1))]=1

result

array([[0., 0., 0.],
       [1., 0., 0.]])
sentence
  • 8,213
  • 4
  • 31
  • 40