numpy.where:如何延迟评估参数?

时间:2016-07-08 23:40:17

标签: python numpy divide-by-zero

我正在使用numpy.where,我想知道是否有一种简单的方法可以避免调用未使用的参数。例如:

import numpy as np
z = np.array([-2, -1, 0, 1, -2])
np.where(z!=0, 1/z, 1)

返回:

array([-0.5, -1. ,  1. ,  1. , -0.5])

但是我得到除以零警告,因为当z为0时,代码仍会评估1/z,即使它没有使用它。

3 个答案:

答案 0 :(得分:2)

您也可以在完成后关闭警告并重新打开 使用上下文管理器errstate

{{1}}

答案 1 :(得分:1)

你可以申请一个面具:

out = numpy.ones_like(z)
mask = z != 0
out[mask] = 1/z[mask]

答案 2 :(得分:0)

scipy has a little utility just for this purpose: https://github.com/scipy/scipy/blob/master/scipy/_lib/_util.py#L26

It's basically a matter of allocating the output array and using np.place (or putmask) to fill exactly what you need.