python - 是什么导致我的函数出现 "ValueError: cannot convert float NaN to integer"

标签 python python-3.x numpy nan

我创建了这个函数:

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.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

关于python - 是什么导致我的函数出现 "ValueError: cannot convert float NaN to integer",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56792194/

相关文章:

python-3.x - 无法在 Mac M1 中安装分词器

javascript - 动态更改 div ID 和 div 内其他元素的 ID

python - 使用 Python .pth 文件假设无权访问 site-packages 目录

python - 对数正态分布变量,求似然度

python - RethinkDB:​​有多少连接?

python - 我将如何循环遍历这个文件元组并写入/读取内容?

python - 更新列表中的 Python for 循环是如何工作的?

python - 如何在python中将二维numpy方形数组旋转45度?

python - 为什么从 np.ones 和 np.zeros 创建的图像都显示黑色空白图像,而将两者结合起来会产生预期的黑白混合图像?

arrays - 数据转换警告: A column-vector y was passed when a 1d array was expected