Let's say I have
>>> import numpy as np
>>> nv = np.array([-1, np.nan, 1])
np.sin
will work as expected
>>> np.sin(nv)
array([-0.84147098, nan, 0.84147098])
However if I try that with vectorize on my own function it'll fail
>>> 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.
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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.