python numpy.where()如何工作? [英] How does python numpy.where() work?

查看:89
本文介绍了python numpy.where()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩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.

推荐答案

它们如何在内部实现您能够将x> 5之类的内容传递给方法的作用?

How do they achieve internally that you are able to pass something like x > 5 into a method?

简短的答案是他们没有.

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()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆