Nan to Num Python

偶尔善良 提交于 2019-12-13 22:33:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!