简体   繁体   English

Python:无法将浮点 NaN 转换为整数

[英]Python: Can't convert float NaN to integer

I apply a moving average logic that returns float.我应用了一个返回浮动的移动平均逻辑。 I convert that float to int before using it to drawing line in OpenCV but getting below error在使用它在 OpenCV 中绘制线条之前,我将该浮点数转换为 int 但低于错误

ValueError: cannot convert float NaN to integer

sample code示例代码

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)

Any suggestion on how to solve it?关于如何解决它的任何建议?

Based on what you have posted, your movingAverage() function is returning NaN at some point.根据您发布的内容,您的movingAverage()函数在某个时候返回NaN

NaN is a special floating point sentinel value, meaning "Not a Number." NaN是一个特殊的浮点标记值,意思是“不是数字”。 In general, Python prefers raising an exception to returning NaN , so things like sqrt(-1) and log(0.0) will generally raise instead of returning NaN .一般来说,Python 更喜欢引发异常而不是返回NaN ,因此sqrt(-1)log(0.0)通常会引发而不是返回NaN However, you may get this value back from some other library.但是,您可能会从其他某个库中获取此值。 A good example might be trying to extract a numeric value from a string cell in a spreadsheet.一个很好的例子可能是尝试从电子表格中的字符串单元格中提取数值。

Standard Python provides math.isnan(x) which you can use to test for NaN .标准 Python 提供math.isnan(x)可用于测试NaN You could either assert against it, raising an exception when it is found, or you could provide a replacement value for the NaN .您可以针对它进行assert ,在找到时引发异常,或者您可以为NaN提供替换值

You appear to be drawing a chart or graph.您似乎正在绘制图表或图形。 My suggestion would be to specifically try to identify this problem (why are you getting this particular NaN ), and then write some code to provide a replacement.我的建议是专门尝试找出这个问题(你为什么要得到这个特定的NaN ),然后编写一些代码来提供替换。

For example, you might determine that column headers in a spreadsheet were responsible for this particular instance of NaN , and fix the code to skip over the column headers.例如,您可能确定电子表格中的列标题负责NaN这个特定实例,并修复代码以跳过列标题。 But then, to prevent a later recurrence, you could check for isnan() in the movingAverage() function, and replace any values with either 0, or the maximum value, effectively treating NaN as 0 or infinity, whichever makes more sense to your graph.但是,为了防止以后再次发生,您可以在movingAverage()函数中检查isnan() ,并将任何值替换为 0 或最大值,有效地将NaN视为 0 或无穷大,以对您更有意义的为准图形。

It seems that your movingAverage() function returns NaN values.您的movingAverage()函数似乎返回NaN 值。

Try尝试

import numpy
int(numpy.nan)

Will give you会给你

ValueError: cannot convert float NaN to integer

To test for NaN测试 NaN

import math, numpy
math.isnan(numpy.nan) 

you can also use:您还可以使用:

    import numpy
    if numpy.isnan(value):
        value = numpy.nan_to_num(value)

which will change the NaN value to (probably 0.0) which can then be converted into an integer.这会将 NaN 值更改为(可能是 0.0),然后可以将其转换为整数。 I'd probably check to make sure that it becoming 0 works for your data.我可能会检查以确保它变为 0 适用于您的数据。

This is my solution to this problem for loading a pandas dataframe into an oracle dbms.这是我将熊猫数据帧加载到 oracle dbms 的解决方案。

{c:VARCHAR2(df[c].str.len().max()) if df[c].str.len().max() + 4 is not np.nan else VARCHAR2(4) 
     for c in df.columns[df.dtypes == 'object'].tolist()}

The key here is x is not np.nan else VARCHAR2(4) in the dict comprehension.这里的关键是x is not np.nan else VARCHAR2(4)在字典理解中。 If you are not familiar with dict comps, read that as value x if not np.nan else other value or if np.nan then x else other value如果您不熟悉 dict comps, value x if not np.nan else other value读作value x if not np.nan else other value or if np.nan then x else other value

this returns a dictionary that can be used to set the dtype to load values into oracle with 4 bytes to spare.这将返回一个字典,该字典可用于设置 dtype 以将值加载到 oracle 中,并保留 4 个字节。 Why 4?为什么是4? Why not?为什么不?

As @mdh pointed out, you can't convert the np.nan value to an integer.正如@mdh 指出的,您不能将 np.nan 值转换为整数。 A solution would be the use of a try and except statement to catch this particular case (but you should make sure, you know, why the functions returns nan's):一个解决方案是使用tryexcept语句来捕捉这个特殊情况(但你应该确保,你知道,为什么函数返回 nan 的):

try:
    x1 = int(avgx1) #avgx1 is returned from the movingaverage function
except ValueError:
    # if ValueError is raised, assign 0 to avgx1
    x1 = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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