NumPy: calculate averages with NaNs removed

前端 未结 12 2527
慢半拍i
慢半拍i 2020-11-27 18:45

How can I calculate matrix mean values along a matrix, but to remove nan values from calculation? (For R people, think na.rm = TRUE).

Here

12条回答
  •  执笔经年
    2020-11-27 19:22

    One more speed check for all proposed approaches:

    Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Jan 19 2016, 12:08:31) [MSC v.1500 64 bit (AMD64)]
    IPython 4.0.1 -- An enhanced Interactive Python.
    
    import numpy as np
    from scipy.stats.stats import nanmean    
    dat = np.random.normal(size=(1000,1000))
    ii = np.ix_(np.random.randint(0,99,size=50),np.random.randint(0,99,size=50))
    dat[ii] = np.nan
    In[185]: def method1():
        mdat = np.ma.masked_array(dat,np.isnan(dat))
        mm = np.mean(mdat,axis=1)
        mm.filled(np.nan) 
    
    In[190]: %timeit method1()
    100 loops, best of 3: 7.09 ms per loop
    In[191]: %timeit [np.mean([l for l in d if not np.isnan(l)]) for d in dat]
    1 loops, best of 3: 1.04 s per loop
    In[192]: %timeit np.array([r[np.isfinite(r)].mean() for r in dat])
    10 loops, best of 3: 19.6 ms per loop
    In[193]: %timeit np.ma.masked_invalid(dat).mean(axis=1)
    100 loops, best of 3: 11.8 ms per loop
    In[194]: %timeit nanmean(dat,axis=1)
    100 loops, best of 3: 6.36 ms per loop
    In[195]: import bottleneck as bn
    In[196]: %timeit bn.nanmean(dat,axis=1)
    1000 loops, best of 3: 1.05 ms per loop
    In[197]: from scipy import stats
    In[198]: %timeit stats.nanmean(dat)
    100 loops, best of 3: 6.19 ms per loop
    

    So the best is 'bottleneck.nanmean(dat, axis=1)' 'scipy.stats.nanmean(dat)' is not faster then numpy.nanmean(dat, axis=1).

提交回复
热议问题