python numpy在哪里返回意外警告 [英] python numpy where returning unexpected warning

查看:92
本文介绍了python numpy在哪里返回意外警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python 2.7,scipy 1.0.0-3

Using python 2.7, scipy 1.0.0-3

显然,我对应该在哪里运行numpy的函数有误解,或者在其操作中存在已知的错误.我希望有人可以告诉我哪些问题,并解释一种解决方法,以消除我试图避免的烦人警告.使用pandas系列where()时,我会得到相同的行为.

Apparently I have a misunderstanding of how the numpy where function is supposed to operate or there is a known bug in its operation. I'm hoping someone can tell me which and explain a work-around to suppress the annoying warning that I am trying to avoid. I'm getting the same behavior when I use the pandas Series where().

为简单起见,我将使用一个numpy数组作为示例.假设我想在数组上应用np.log(),仅对于条件而言,值是有效输入,即myArray> 0.0.对于不应应用此功能的值,我想将输出标志设置为-999.9:

To make it simple, I'll use a numpy array as my example. Say I want to apply np.log() on the array and only so for the condition a value is a valid input, i.e., myArray>0.0. For values where this function should not be applied, I want to set the output flag of -999.9:

myArray = np.array([1.0, 0.75, 0.5, 0.25, 0.0])
np.where(myArray>0.0, np.log(myArray), -999.9)

我希望numpy.where()不会抱怨数组中的0.0值,因为那里的条件为False,但是确实如此,并且它似乎实际上针对该False条件执行了:

I expected numpy.where() to not complain about the 0.0 value in the array since the condition is False there, yet it does and it appears to actually execute for that False condition:

-c:2: RuntimeWarning: divide by zero encountered in log 
array([  0.00000000e+00,  -2.87682072e-01,  -6.93147181e-01,
        -1.38629436e+00,  -9.99900000e+02])

numpy文档指出:

如果给定x和y并且输入数组为一维,则等效于: [如果是zip(condition,x,y)中的(c,xv,yv)则为yv,则为xv]

If x and y are given and input arrays are 1-D, where is equivalent to: [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]

我谨此声明与

[np.log(val) if val>0.0 else -999.9 for val in myArray]

完全不提供警告:

[0.0, -0.2876820724517809, -0.69314718055994529, -1.3862943611198906, -999.9] 

那么,这是一个已知的错误吗?我不想抑制整个代码的警告.

So, is this a known bug? I don't want to suppress the warning for my entire code.

推荐答案

仅可以使用可选的where参数在相关位置对log进行评估

You can have the log evaluated at the relevant places only using its optional where parameter

np.where(myArray>0.0, np.log(myArray, where=myArray>0.0), -999.9)

或更有效

mask = myArray > 0.0
np.where(mask, np.log(myArray, where=mask), -999)

或者如果您发现"double where"丑陋

or if you find the "double where" ugly

np.log(myArray, where=myArray>0.0, out=np.full(myArray.shape, -999.9))

这三个中的任何一个都应禁止显示警告.

Any one of those three should suppress the warning.

这篇关于python numpy在哪里返回意外警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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