问题描述
我正在玩numpy
并仔细阅读文档,我遇到了一些魔术.即我在说numpy.where()
:
I am playing with numpy
and digging through documentation and I have come across some magic. Namely I am talking about numpy.where()
:
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
它们如何在内部实现您能够将类似x > 5
的内容传递给方法的功能?我想这可能与__gt__
有关,但我正在寻找详细的解释.
How do they achieve internally that you are able to pass something like x > 5
into a method? I guess it has something to do with __gt__
but I am looking for a detailed explanation.
推荐答案
简短的答案是他们没有.
The short answer is that they don't.
对numpy数组进行任何逻辑运算都会返回一个布尔数组. (即__gt__
,__lt__
等都返回给定条件为true的布尔数组).
Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__
, __lt__
, etc all return boolean arrays where the given condition is true).
例如
x = np.arange(9).reshape(3,3)
print x > 5
产量:
array([[False, False, False],
[False, False, False],
[ True, True, True]], dtype=bool)
这就是为什么如果x
是一个numpy数组,类似if x > 5:
的对象会引发ValueError的相同原因.这是一个True/False值数组,而不是单个值.
This is the same reason why something like if x > 5:
raises a ValueError if x
is a numpy array. It's an array of True/False values, not a single value.
此外,可以用布尔数组对numpy数组进行索引.例如.在这种情况下,x[x>5]
产生[6 7 8]
.
Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5]
yields [6 7 8]
, in this case.
老实说,您实际上需要numpy.where
的情况很少见,但它只返回布尔数组为True
的索引.通常,您可以通过简单的布尔索引来完成所需的工作.
Honestly, it's fairly rare that you actually need numpy.where
but it just returns the indicies where a boolean array is True
. Usually you can do what you need with simple boolean indexing.
这篇关于python numpy.where()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!