问题描述
让我们说我们有以下功能:
Let's say we have the following function:
def f(x, y):
if y == 0:
return 0
return x/y
这正常工作与标量值。不幸的是,当我尝试使用numpy的阵列以 X
和是
比较ÿ== 0
被视为一个数组操作导致的错误:
This works fine with scalar values. Unfortunately when I try to use numpy arrays for x
and y
the comparison y == 0
is treated as an array operation which results in an error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-9884e2c3d1cd> in <module>()
----> 1 f(np.arange(1,10), np.arange(10,20))
<ipython-input-10-fbd24f17ea07> in f(x, y)
1 def f(x, y):
----> 2 if y == 0:
3 return 0
4 return x/y
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我试图用 np.vectorize
但它不会有所作为,在code还是失败,出现同样的错误。 np.vectorize
是一个选项,给出结果我的期望。
np.vectorize
is one option which gives the result I expect.
这是我能想到的唯一解决办法是使用 np.where
在是
阵列像
The only solution that I can think of is to use np.where
on the y
array with something like:
def f(x, y):
np.where(y == 0, 0, x/y)
不为标量工作。
有没有更好的方式来写它包含一个if语句的函数吗?它应与标量和数组。
Is there a better way to write a function which contains an if statement? It should work with both scalars and arrays.
推荐答案
您可以使用屏蔽数组将执行师只有在 Y = 0
:
You can use a masked array that will perform the division only where y!=0
:
def f(x, y):
x = np.atleast_1d(np.array(x))
y = np.atleast_1d(np.ma.array(y, mask=(y==0)))
ans = x/y
ans[ans.mask]=0
return np.asarray(ans)
这篇关于如何向量化包含if语句的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!