How to get a new numpy array based on conditions of two other numpy arrays using only numpy operations?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping
--
Chapters
00:00 Question
00:55 Accepted answer (Score 0)
02:03 Thank you
--
Full question
https://stackoverflow.com/questions/6611...
Accepted answer links:
https://wiki.python.org/moin/BitwiseOper...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #numpy
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping
--
Chapters
00:00 Question
00:55 Accepted answer (Score 0)
02:03 Thank you
--
Full question
https://stackoverflow.com/questions/6611...
Accepted answer links:
https://wiki.python.org/moin/BitwiseOper...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #numpy
#avk47
ACCEPTED ANSWER
Score 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.