[英]np.vectorize and nan - how can I make them play nice?
Let's say I have 假设我有
>>> import numpy as np
>>> nv = np.array([-1, np.nan, 1])
np.sin
will work as expected np.sin
将按预期工作
>>> np.sin(nv)
array([-0.84147098, nan, 0.84147098])
However if I try that with vectorize on my own function it'll fail 但是,如果我在自己的函数上尝试使用vectorize,它将失败
>>> def noneg(n):
if n < 0:
return 0
return n
>>> noneg(nv)
...
ValueError: cannot convert float NaN to integer
This is because the initize value returned by noneg is the integer zero and then we get nan
which is a float. 这是因为noneg返回的初始化值是整数零,然后我们得到了一个浮点数nan
。
The solution I've found so far is: 到目前为止,我发现的解决方案是:
>>> @np.vectorize
def noneg(n):
if not np.isnan(n) and n < 0:
return n.__class__(0)
return n
>>> noneg(nv)
array([ 0., nan, 1.])
However this looks ugly, is there a better way to ignore nan
in vectorize? 但这看起来很丑,在矢量化中是否有更好的方法忽略nan
?
Hmm, you already wrote the answer? 嗯,您已经写下答案了?
def noneg(n):
if n < 0:
return n.__class__(0)
return n
noneg(nv)
The problem here is the variable 0 is not concerning your input type, I think. 我认为这里的问题是变量0与您的输入类型无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.