将nan值转换为零 [英] convert nan value to zero
问题描述
我有一个二维的numpy数组.此数组中的某些值为NaN
.我想使用此数组执行某些操作.例如考虑数组:
I have a 2D numpy array. Some of the values in this array are NaN
. I want to perform certain operations using this array. For example consider the array:
[[ 0. 43. 67. 0. 38.]
[ 100. 86. 96. 100. 94.]
[ 76. 79. 83. 89. 56.]
[ 88. NaN 67. 89. 81.]
[ 94. 79. 67. 89. 69.]
[ 88. 79. 58. 72. 63.]
[ 76. 79. 71. 67. 56.]
[ 71. 71. NaN 56. 100.]]
我试图每次取一行,以相反的顺序对其进行排序,以从该行中获取最多3个值并取其平均值.我尝试的代码是:
I am trying to take each row, one at a time, sort it in reversed order to get max 3 values from the row and take their average. The code I tried is:
# nparr is a 2D numpy array
for entry in nparr:
sortedentry = sorted(entry, reverse=True)
highest_3_values = sortedentry[:3]
avg_highest_3 = float(sum(highest_3_values)) / 3
这不适用于包含NaN
的行.我的问题是,是否有一种快速的方法可以将2D numpy数组中的所有NaN
值都转换为零,这样我在排序和其他尝试做的事情上都不会遇到问题.
This does not work for rows containing NaN
. My question is, is there a quick way to convert all NaN
values to zero in the 2D numpy array so that I have no problems with sorting and other things I am trying to do.
推荐答案
这应该有效:
from numpy import *
a = array([[1, 2, 3], [0, 3, NaN]])
where_are_NaNs = isnan(a)
a[where_are_NaNs] = 0
在上述情况下,_are_NaNs为:
In the above case where_are_NaNs is:
In [12]: where_are_NaNs
Out[12]:
array([[False, False, False],
[False, False, True]], dtype=bool)
这篇关于将nan值转换为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!