我如何使用链式比较对数组进行布尔化掩盖? [英] How do I boolean mask an array using chained comparisons?
问题描述
如何使用一对不等式来过滤一个numpy数组,例如:
How can I filter a numpy array using a pair of inequalities, such as:
>>> a = np.arange(10)
>>> a[a <= 6]
array([0, 1, 2, 3, 4, 5, 6])
>>> a[3 < a]
array([4, 5, 6, 7, 8, 9])
>>>
>>> a[3 < a <= 6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
如果我尝试a.all(3 < a <= 6)
np.array([x for x in a if 3 < x <= 6])
可以工作,但是看起来很讨厌.什么是正确的方法?
np.array([x for x in a if 3 < x <= 6])
works, but it seems nasty. What's the right way to do this?
推荐答案
您需要这样做:
a[(3 < a) & (a <= 6)]
这是python中的疣".在python中,(3 < a <=6)
被翻译为((3 < a) and (a <= 6))
.但是numpy数组不适用于and
操作,因为python不允许and
和or
运算符重载.因此,numpy使用&
和|
.大约一年前,有一些关于解决此问题的讨论,但是自那以后,我对此似乎没有多少关注.
It's a "wart" in python. In python (3 < a <=6)
is translated to ((3 < a) and (a <= 6))
. However numpy arrays don't work with the and
operation because python doesn't allow overloading of the and
and or
operators. Because of that numpy uses &
and |
. There was some discussion about fixing this about a year ago, but I haven't seem much about it since.
http://mail.python.org/pipermail/python-dev/2012-March/117510.html
这篇关于我如何使用链式比较对数组进行布尔化掩盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!