28

ナンを避けて配列(A)の平均値を計算する方法は?

import numpy as np 
A = [5    nan    nan    nan    nan  10]
M = np.mean(A[A!=nan]) does not work
Any idea?
4

2 に答える 2

30

使用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
于 2013-11-08T06:02:39.743 に答える