如何计算避免nan的数组(A)的平均值?
import numpy as np
A = [5 nan nan nan nan 10]
M = np.mean(A[A!=nan]) does not work
Any idea?
另一种可能性如下:
import numpy
from scipy.stats import nanmean # nanmedian exists too, if you need it
A = numpy.array([5, numpy.nan, numpy.nan, numpy.nan, numpy.nan, 10])
print nanmean(A) # gives 7.5 as expected
我想这看起来比已经给出的其他解决方案更优雅(和可读)
编辑:显然(@Jaime)报告说这个功能已经直接存在于最新的numpy
(1.8)中,所以如果你有那个版本就不需要import scipy.stats
了numpy
:
import numpy
A = numpy.array([5, numpy.nan, numpy.nan, numpy.nan, numpy.nan, 10])
print numpy.nanmean(A)
第一个解决方案也适用于没有最新版本numpy
(如我)的人
使用numpy.isnan
:
>>> import numpy as np
>>> A = np.array([5, np.nan, np.nan, np.nan, np.nan, 10])
>>> np.isnan(A)
array([False, True, True, True, True, False], dtype=bool)
>>> ~np.isnan(A)
array([ True, False, False, False, False, True], dtype=bool)
>>> A[~np.isnan(A)]
array([ 5., 10.])
>>> A[~np.isnan(A)].mean()
7.5
因为你不能nan
比较nan
:
>>> np.nan == np.nan
False
>>> np.nan != np.nan
True
>>> np.isnan(np.nan)
True