Say I construct two numpy arrays:
a = np.array([np.NaN, np.NaN])
b = np.array([np.NaN, np.NaN, 3])
Now I find that np.mean
ret
A NaN
value is defined to not be equal to itself:
>>> float('nan') == float('nan')
False
>>> np.NaN == np.NaN
False
You can use a Python conditional and the property of a nan never being equal to itself to get this behavior:
>>> a = np.array([np.NaN, np.NaN])
>>> b = np.array([np.NaN, np.NaN, 3])
>>> np.NaN if np.all(a!=a) else np.nanmean(a)
nan
>>> np.NaN if np.all(b!=b) else np.nanmean(b)
3.0
You can also do:
import warnings
import numpy as np
a = np.array([np.NaN, np.NaN])
b = np.array([np.NaN, np.NaN, 3])
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
x=np.nanmean(a)
except RuntimeWarning:
x=np.NaN
print x