numpy.where : how to delay evaluating parameters?

我怕爱的太早我们不能终老 提交于 2019-12-11 06:10:58

问题


I am using numpy.where, and I was wondering if there was a simply way to avoid calling the unused parameter. Example:

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

returns:

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

but I get a divide by zero warning because when z was 0, the code still evaluates 1/z even though it doesn't use it.


回答1:


You can also turn off the warning and turn it back on after you are done using the context manager errstate:

with np.errstate(divide='ignore'):
    np.where(z!=0, 1/z, 1)



回答2:


You can apply a mask:

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



回答3:


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.



来源:https://stackoverflow.com/questions/38276813/numpy-where-how-to-delay-evaluating-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!