3

Let's say I have np.array of a = [0, 1, 1, 0, 0, 1] and b = [1, 1, 0, 0, 0, 1]

I want a new matrix c such that if a[i] = 0 and b[i] = 0 then c[i] = True

I've tried using c = np.where(a == 0 & b==0) but seems this won't work on two arrays.

Ultimately I want a count of '0's that are true in both cases and '1's that are true in both cases without using any loops and external libraries. Please advise.

1 Answers1

0

Here is my solution:

Your logic expression is nothing but c = NOT (a OR b). This means, you want c[i] = True, only if both a[i] and b[i] are zero. The OR can be achieved by adding the two arrays. We then convert the array into a boolean type and invert it.

import numpy as np

a = np.array([0, 1, 1, 0, 0, 1])
b = np.array([1, 1, 0, 0, 0, 1])

c = np.invert((a+b).astype('bool'))

If you then want to count the number of zeros you can simply perform

n_zeros = np.sum(c)

More general solution:

If you want your array c[i] = True if a[i] == a0 and b[i] == b0, you can do:

c = (a == a0) & (b == b0)

The conditions a == a0 and b == b0 return each a boolean array with the truth value of the condition for each individual array element. The bitwise operator & performs an element-wise logical AND. For more bitwise operators see https://wiki.python.org/moin/BitwiseOperators.

Mar H.
  • 86
  • 1
  • 2
  • That's an interesting answer. But what if I want ```if a[i] = 0 and b[i] = 1``` then ```c[i] = True```? Would be nice to be able to use condition. –  Feb 09 '21 at 10:05
  • I added a more general solution, I hope that works for you. You cannot use logical operators on numpy arrays you would need bitwise operators, see https://stackoverflow.com/questions/21415661/. So in this case instead of the multiplication you could use &. – Mar H. Feb 09 '21 at 10:15
  • Yes this is it! This is dot product right? But why does it work this way? Thanks. –  Feb 09 '21 at 10:18
  • No, the `*` is the element-wise multiplication of the two arrays in the brackets, which in turn are boolean arrays. If you multiply two booleans, the result is `True` if both are `True`, otherwise it's `False`. So this is equivalent to an logical AND. – Mar H. Feb 09 '21 at 10:23
  • I edited my answer, such that it uses bitwise operators instead of aritmethic operators, it should be clearer now. – Mar H. Feb 09 '21 at 10:26