[英]How to get a new numpy array based on conditions of two other numpy arrays using only numpy operations?
Let's say I have np.array of a = [0, 1, 1, 0, 0, 1]
and b = [1, 1, 0, 0, 0, 1]
假设我有a = [0, 1, 1, 0, 0, 1]
和b = [1, 1, 0, 0, 0, 1]
的 np.array
I want a new matrix c such that if a[i] = 0
and b[i] = 0
then c[i] = True
我想要一个新矩阵 c 使得如果a[i] = 0
和b[i] = 0
那么c[i] = True
I've tried using c = np.where(a == 0 & b==0)
but seems this won't work on two arrays.我试过使用c = np.where(a == 0 & b==0)
但似乎这不适用于两个 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.最终,我想要在不使用任何循环和外部库的情况下计算两种情况下都为真的'0'和两种情况下都为真的'1'。 Please advise.请指教。
Here is my solution:这是我的解决方案:
Your logic expression is nothing but c = NOT (a OR b).您的逻辑表达式不过是 c = NOT (a OR b)。 This means, you want c[i] = True
, only if both a[i]
and b[i]
are zero.这意味着,只有当a[i]
和b[i]
都为零时,您才需要c[i] = True
。 The OR can be achieved by adding the two arrays. OR 可以通过添加两个 arrays 来实现。 We then convert the array into a boolean type and invert it.然后我们将数组转换为 boolean 类型并将其反转。
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[i] = True
if a[i] == a0 and b[i] == b0
,你可以这样做:
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.条件a == a0
和b == b0
分别返回一个 boolean 数组,其中包含每个单独数组元素的条件真值。 The bitwise operator &
performs an element-wise logical AND.按位运算符&
执行按元素逻辑与。 For more bitwise operators see https://wiki.python.org/moin/BitwiseOperators .有关更多按位运算符,请参阅https://wiki.python.org/moin/BitwiseOperators 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.