numpy-1.13 ufuncs 中的“where”子句

Kes*_*sel 5 python numpy numpy-ufunc

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

import numpy as np
a = np.linspace(-1, 1, 10)
np.sqrt(a, where=a>0) * (a>0)
Run Code Online (Sandbox Code Playgroud)

在 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
Run Code Online (Sandbox Code Playgroud)

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

Kes*_*sel 3

供将来参考:这被证明是 numpy 中的一个错误。它在下一个 numpy 版本(大概是版本 1.13.1)中修复。

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