Python:无法将float NaN转换为整数

nad*_*nad 0 python opencv

我应用一个返回浮动的移动平均逻辑.我将该float转换为int,然后将其用于在OpenCV中绘制线但是低于错误

ValueError: cannot convert float NaN to integer
Run Code Online (Sandbox Code Playgroud)

示例代码

def movingAverage(avg, new_sample, N=20):
    if (avg == 0):
    return new_sample
    avg -= avg / N;
    avg += new_sample / N;
    return avg;

x1 = int(avgx1) #avgx1 is returned from the movingaverage function
y1 = int(avgy1) 
x2 = int(avgx2)
y2 = int(avgy2)
cv2.line(img, (x1, y1), (x2, y2), [255,255,255], 12)
Run Code Online (Sandbox Code Playgroud)

有关如何解决的任何建议?

agh*_*ast 6

根据您发布的内容,您的movingAverage()功能会NaN在某个时刻返回.

NaN是一个特殊的浮点标记值,意思是"不是数字".一般来说,Python更喜欢引发返回的异常NaN,所以像sqrt(-1)和之类的东西log(0.0)通常会提高而不是返回NaN.但是,您可以从其他库中获取此值.一个很好的例子可能是尝试从电子表格中的字符串单元格中提取数值.

标准Python提供了math.isnan(x)可用于测试的内容NaN.你既可以assert反对,引发异常的时候才发现,或者你可以提供一个替代值NaN.

您似乎正在绘制图表或图表.我的建议是专门尝试识别这个问题(为什么你得到这个特殊的NaN),然后编写一些代码来提供替代.

例如,您可能确定电子表格中的列标题负责此特定实例NaN,并修复代码以跳过列标题.但是,为了防止以后再次出现,您可以isnan()movingAverage()函数中检查,并将任何值替换为0或最大值,有效地NaN视为0或无穷大,无论哪个对图表更有意义.


mdh*_*mdh 5

您的movingAverage()函数似乎返回 NaN 值。

尝试

import numpy
int(numpy.nan)
Run Code Online (Sandbox Code Playgroud)

会给你

ValueError: cannot convert float NaN to integer
Run Code Online (Sandbox Code Playgroud)

测试 NaN

import math, numpy
math.isnan(numpy.nan) 
Run Code Online (Sandbox Code Playgroud)