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.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.