【发布时间】:2014-08-30 01:16:55
【问题描述】:
假设我们有以下函数:
def f(x, y):
if y == 0:
return 0
return x/y
这适用于标量值。不幸的是,当我尝试对x 和y 使用numpy 数组时,比较y == 0 被视为导致错误的数组操作:
---------------------------------------------------------------------------
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,但它没有任何区别,代码仍然失败并出现同样的错误。np.vectorize 是一个选项,它给出了我期望的结果。 p>
我能想到的唯一解决方案是在y 数组上使用np.where,例如:
def f(x, y):
np.where(y == 0, 0, x/y)
这不适用于标量。
有没有更好的方法来编写一个包含 if 语句的函数?它应该适用于标量和数组。
【问题讨论】:
-
您是说您想为
y传递一个numpy 数组,但为x传递一个数字?反之亦然,或两者兼而有之? -
如果您将 y 和 x 包装在
np.asarray中,where版本将起作用。但请注意,x/y在任何地方都会被评估,因此如果有任何y==0,您可能会收到警告或异常(取决于您的浮点标志)。 -
@BrenBarn
x和y在第二种情况下都是数组。编辑了我的答案以使其更加明确。 -
np.vectorize在这里工作正常:) -
@moarningsun 你能用代码发布答案吗?
标签: python arrays numpy vectorization