mean, nanmean and warning: Mean of empty slice

前端 未结 2 2173
自闭症患者
自闭症患者 2020-12-14 05:07

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

2条回答
  •  时光取名叫无心
    2020-12-14 06:00

    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    
    

提交回复
热议问题