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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42463084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:42:53  来源:igfitidea点击:

Python: Can't convert float NaN to integer

pythonopencv

提问by nad

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?

关于如何解决它的任何建议?

回答by aghast

Based on what you have posted, your movingAverage()function is returning NaNat some point.

根据您发布的内容,您的movingAverage()函数会NaN在某个时候返回。

NaNis a special floating point sentinel value, meaning "Not a Number." 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. 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.

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

Standard Python provides math.isnan(x)which you can use to test for NaN. You could either assertagainst it, raising an exception when it is found, or you could provide a replacement valuefor the NaN.

标准 Python 提供了math.isnan(x)可用于测试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 particularinstance of NaN, and fix the code to skip over the column headers. 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 NaNas 0 or infinity, whichever makes more sense to your graph.

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

回答by mdh

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) 

回答by Chief_Peon

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. If you are not familiar with dict comps, read that as value x if not np.nan else other valueor if np.nan then x else other value

这里的关键x is not np.nan else VARCHAR2(4)在于对字典的理解。如果您不熟悉 dict comps,请将其阅读为value x if not np.nan else other valueif 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. Why 4? Why not?

这将返回一个字典,可用于设置 dtype 以将值加载到 oracle 中,并保留 4 个字节。为什么是4?为什么不?

回答by user1999418

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. I'd probably check to make sure that it becoming 0 works for your data.

这会将 NaN 值更改为(可能是 0.0),然后可以将其转换为整数。我可能会检查以确保它变为 0 适用于您的数据。