ナンを避けて配列(A)の平均値を計算する方法は?
import numpy as np
A = [5 nan nan nan nan 10]
M = np.mean(A[A!=nan]) does not work
Any idea?
使用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