Python: Can’t convert float NaN to integer

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

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

Standard Python provides math.isnan(x) which you can use to test for NaN. You could either assert against it, raising an exception when it is found, or you could provide a replacement value for the 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.

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

Leave a Comment