简体   繁体   中英

What is causing “ValueError: cannot convert float NaN to integer” in my function

I have created this function:

import numpy as np 


def npp_tool(pb_opt, chlor_a, daylight, irrFunc, z_eu):
            if daylight == 0 or daylight == np.nan:
                return -32767
            elif pb_opt == np.nan:
                return -32767
            elif chlor_a == -32767 or daylight == np.nan:
                return -32767
            elif irrFunc == np.nan:
                return -32767
            elif z_eu == np.nan:
                return -32767
            else:
                return pb_opt * chlor_a * daylight * irrFunc * z_eu

that converts np.nan values in the inputs to integers

npp_vec = np.vectorize(npp_tool)
npp = npp_vec(pb_opt, chlor_a, daylight, irrFunc, z_eu)

But when I run the above code I stil get the error message "ValueError: cannot convert float NaN to integer" :

"---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-7ad956e7f0a2> in <module>
----> 1 npp = npp_vec(pb_opt, chlor_a, daylight, irrFunc, z_eu)

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\numpy\lib\function_base.py in __call__(self, *args, **kwargs)
   2089             vargs.extend([kwargs[_n] for _n in names])
   2090 
-> 2091         return self._vectorize_call(func=func, args=vargs)
   2092 
   2093     def _get_ufunc_and_otypes(self, func, args):

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\numpy\lib\function_base.py in _vectorize_call(self, func, args)
   2168 
   2169             if ufunc.nout == 1:
-> 2170                 res = array(outputs, copy=False, subok=True, dtype=otypes[0])
   2171             else:
   2172                 res = tuple([array(x, copy=False, subok=True, dtype=t)

ValueError: cannot convert float NaN to integer" 

What am I doing wrong in my function to cause this?

You can't compare np.nan with np.nan using ==

you should use np.isnan :

so change all your comparisons to:

elif np.isnan(pb_opt):

and so on

eg:

In[71]:
np.nan==np.nan

Out[71]: False

So the above comparison fails, whilst isnan works:

In[73]:
np.isnan(np.nan)

Out[72]: True

NaN has the property that it can't be compared with itself:

In[73]:
np.nan != np.nan

Out[73]: True

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM