结合逻辑语句和numpy的阵列 [英] Combining logic statements AND in numpy array
本文介绍了结合逻辑语句和numpy的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是选择元素,当两个条件真
在矩阵的方式吗?
在R,它基本上是可以结合的载体的布尔
What would be the way to select elements when two conditions are True
in a matrix?
In R, it is basically possible to combine vectors of booleans.
那么,我的目标:
A = np.array([2,2,2,2,2])
A < 3 and A > 1 # A < 3 & A > 1 does not work either
Evals到:
ValueError错误:与多个元件的阵列的真值是不明确的。使用a.any()或a.all()
Evals to: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
应该EVAL为:
array([True,True,True,True,True])
我的解决方法通常是总结这些布尔向量和等同于2,但必须有一个更好的办法。这是什么?
My workaround usually is to sum these boolean vectors and equate to 2, but there must be a better way. What is it?
推荐答案
您可以只使用&安培;
,例如:
x = np.arange(10)
(x<8) & (x>2)
给
array([False, False, False, True, True, True, True, True, False, False], dtype=bool)
的一些细节:
- 这工作,因为
&安培;
是简写numpy的ufuncbitwise_and
,这对于布尔
类型相同逻辑与
。也就是说,这也可以作为结果bitwise_and(以下(X,8),较大(X,2))
拼写 - 您需要的,因为在numpy的括号
&安培;
具有较高的precedence比&LT;
和&GT;
-
和
不起作用,因为它是暧昧numpy的阵列,因此而不是猜测,numpy的抛出异常。
- This works because
&
is shorthand for the numpy ufuncbitwise_and
, which for thebool
type is the same aslogical_and
. That is, this could also be spelled out asbitwise_and(less(x,8), greater(x,2))
- You need the parentheses because in numpy
&
has higher precedence than<
and>
and
does not work because it is ambiguous for numpy arrays, so rather than guess, numpy raise the exception.
这篇关于结合逻辑语句和numpy的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文