Home > Software engineering >  One Mask subtracting another mask on numpy
One Mask subtracting another mask on numpy

Time:02-03

I am new to numpy so any help is appreciated. Say I have two 1-0 masks A and B in 2D numpy array with the same dimension. Now I would like to do logical operation to subtract B from A

A B Expected Result 
1 1  0
1 0  1
0 1  0
0 0  0

But i am not sure it works when a = 0 and b = 1 where a and b are elements from A and B respectively for A = A - B So I do something like

A = np.where(B == 0, A, 0)

But this is not very readable. Is there a better way to do that Because for logical or, I can do something like

A = A | B

Is there a similar operator that I can do the subtraction?

CodePudding user response:

Since subtraction is not supported for booleans, you need to cast at least one of the arrays to an integer dtype before subtracting. If you want to make sure that the result can't be negative, you can use numpy.maximum.

np.maximum(A.astype(int) - B, 0)
  • Related