我创建了此功能:
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
会将输入中的np.nan值转换为整数
npp_vec = np.vectorize(npp_tool)
npp = npp_vec(pb_opt, chlor_a, daylight, irrFunc, z_eu)
但是当我运行上面的代码时,我仍然收到错误消息“ ValueError:无法将float NaN转换为整数”:
"---------------------------------------------------------------------------
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"
我在执行该功能时做错了什么?
答案 0 :(得分:3)
您无法使用np.nan
将np.nan
与==
进行比较
您应该使用np.isnan
:
因此将所有比较更改为:
elif np.isnan(pb_opt):
以此类推
例如:
In[71]:
np.nan==np.nan
Out[71]: False
因此,以上比较失败,而isnan
起作用:
In[73]:
np.isnan(np.nan)
Out[72]: True
NaN
具有无法与自身进行比较的属性:
In[73]:
np.nan != np.nan
Out[73]: True