脾气暴躁的地方和除以零 [英] Numpy where and division by zero
问题描述
我需要通过以下方式(旧版代码)计算x
:
I need to compute x
in the following way (legacy code):
x = numpy.where(b == 0, a, 1/b)
我想它可以在 python-2.x (因为它在 python-2.7 代码),但在 python-3.x (if b = 0
它返回错误).
I suppose it worked in python-2.x (as it was in a python-2.7 code), but it does not work in python-3.x (if b = 0
it returns an error).
我如何使其在python-3.x中工作?
How do I make it work in python-3.x?
错误消息(Python 3.6.3):
error message (Python 3.6.3):
ZeroDivisionError: division by zero
推荐答案
The numpy.where
documentation states:
如果给出了
x
和y
并且输入数组为一维,则where
为 等同于::
If
x
andy
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)]
那么为什么您会看到错误?举个简单的例子:
So why do you see the error? Take this trivial example:
c = 0
result = (1 if c==0 else 1/c)
# 1
到目前为止,一切都很好.首先检查if c==0
,结果为1
.该代码不会尝试评估1/c
.这是因为Python解释器处理 lazy 三元运算符,因此仅求值适当的表达式.
So far so good. if c==0
is checked first and the result is 1
. The code does not attempt to evaluate 1/c
. This is because the Python interpreter processes a lazy ternary operator and so only evaluates the appropriate expression.
现在让我们将其翻译为numpy.where
方法:
Now let's translate this into numpy.where
approach:
c = 0
result = (xv if c else yv for (c, xv, yv) in zip([c==0], [1], [1/c]))
# ZeroDivisionError
在应用逻辑之前,在评估zip([c==0], [1], [1/c])
时发生错误.生成器表达式本身无法求值.作为功能,numpy.where
不能也确实不能复制Python三元表达式的惰性计算.
The error occurs in evaluating zip([c==0], [1], [1/c])
before even the logic is applied. The generator expression itself can't be evaluated. As a function, numpy.where
does not, and indeed cannot, replicate the lazy computation of Python's ternary expression.
这篇关于脾气暴躁的地方和除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!