python将nan, inf转为特定的数字

2023-04-27,,

最近,处理两个矩阵的点除,得到结果后,再作其他的计算,发现有些内置的函数不work;查看得到的数据,发现有很多nan和inf,导致python的基本函数运行不了,这是因为在除的过程中分母出现0的缘故。为了将结果能够被python其他函数处理,尤其numpy库,需要将nan,inf转为python所能识别的类型。这里将nan,inf替换0作为例子。

1. 代码

import numpy as np
a = np.array([[np.nan, np.nan, 1, 2], [np.inf, np.inf, 3, 4], [1, 1, 1, 1], [2, 2, 2, 2]])
print a
where_are_nan = np.isnan(a)
where_are_inf = np.isinf(a)
a[where_are_nan] = 0
a[where_are_inf] = 0
print a
print np.mean(a)

2. 运行结果

[[ nan  nan   1.   2.]
 [ inf  inf   3.   4.]
 [  1.   1.   1.   1.]
 [  2.   2.   2.   2.]]
[[ 0.  0.  1.  2.]
 [ 0.  0.  3.  4.]
 [ 1.  1.  1.  1.]
 [ 2.  2.  2.  2.]]
1.375

参考资料:http://stackoverflow.com/questions/5124376/convert-nan-value-to-zero

python将nan, inf转为特定数字的相关教程结束。

《python将nan, inf转为特定的数字.doc》

下载本文的Word格式文档,以方便收藏与打印。