python 用数组替换操作后的 NaN 值零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1803516/
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
replace the NaN value zero after an operation with arrays
提问by ricardo
how can I replace the NaN value in an array, zero if an operation is performed such that as a result instead of the NaN value is zero operations as
如何替换数组中的 NaN 值,如果执行操作则为零,因此结果而不是 NaN 值是零操作,如
0 / 0 = NaN can be replaced by 0
0 / 0 = NaN 可以替换为 0
回答by Dave Webb
If you have Python 2.6 you have the math.isnan()
function to find NaN
values.
如果你有 Python 2.6,你就有math.isnan()
查找NaN
值的功能。
With this we can use a list comprehension to replace the NaN
values in a list as follows:
有了这个,我们可以使用列表理解来替换列表中的NaN
值,如下所示:
import math
mylist = [0 if math.isnan(x) else x for x in mylist]
If you have Python 2.5 we can use the NaN != NaN
trick from this questionso you do this:
如果你有 Python 2.5,我们可以使用这个问题中的NaN != NaN
技巧,所以你可以这样做:
mylist = [0 if x != x else x for x in mylist]
回答by SoonSYJ
import numpy
a=numpy.array([1,2,3,'NaN',4])
s=numpy.isnan(a)
a[s]=0.0