【问题标题】:What is causing "ValueError: cannot convert float NaN to integer" in my function是什么导致我的函数中出现“ValueError:无法将浮点 NaN 转换为整数”
【发布时间】:2019-11-09 13:03:17
【问题描述】:

我已经创建了这个函数:

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: 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" 

我在我的函数中做错了什么导致这种情况?

【问题讨论】:

  • 虽然不是直接的问题,但在使用np.vectorize 时要小心。注意它如何选择返回dtype,并考虑使用otypes参数。

标签: python python-3.x numpy nan


【解决方案1】:

您无法使用==np.nannp.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

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2020-04-10
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多