"where" numpy-1.13 ufuncs 中的子句

"where" clause in numpy-1.13 ufuncs

我偶尔会在 numpy 的 ufunc 中使用 where 子句。例如,以下内容:

import numpy as np
a = np.linspace(-1, 1, 10)
np.sqrt(a, where=a>0) * (a>0)

在 Numpy 1.12 及更早版本中,这曾经尽可能给我平方根值,否则为零。

最近,我升级到了 numpy 1.13。上面的代码现在给我以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Automatic allocation was requested for an iterator operand, and it was flagged as readable, but buffering  without delayed allocation was enabled

我认为这正是 where 子句应该使用的方式,但也许我错了。所以我有两个问题:第一,这段代码有什么问题;其次,实现我的目标的推荐方法是什么?

以供日后参考:这原来是 numpy 中的一个错误。它 has been fixed 用于下一个 numpy 版本,大概是版本 1.13.1。

1.13.0 的解决方法是明确向 ufunc 提供 out 参数。在上面的示例中,np.sqrt(a, where=a>0, out=np.zeros(a.shape)) 有效。