问题
I have multiple array that for those I calculate a linear regression, but sometimes it gives me 0/0 values which gives me a 'NaN'. I know that to convert an array where there are numbers that are NaN you can convert them using numpy.nan_to_num. But what if I want to convert a single value that's not in a array, but a result of a linear regression calculation?
EDIT: It's not a duplicate question (convert nan value to zero ) since I'm referring to a item/result that is not in a array
回答1:
numpy.nan_to_num
works fine on scalars.
>>> import numpy as np
>>> np.nan_to_num(float('inf'))
1.7976931348623157e+308
>>> np.nan_to_num(float('nan'))
0.0
>>> np.nan_to_num(float('-inf'))
-1.7976931348623157e+308
回答2:
You can just check if your variable of choice is NaN with math.isnan. If it is, change it to the number of your choice. Like this:
>>> import math
>>> x = float("nan")
>>> x
nan
>>> if math.isnan(x):
... x = 123 # just an example
...
>>> x
123
来源:https://stackoverflow.com/questions/27968236/nan-to-num-python