Fast check for NaN in NumPy

后端 未结 7 1958
时光说笑
时光说笑 2021-01-30 02:39

I\'m looking for the fastest way to check for the occurrence of NaN (np.nan) in a NumPy array X. np.isnan(X) is out of the question, since

7条回答
  •  星月不相逢
    2021-01-30 03:22

    Even there exist an accepted answer, I'll like to demonstrate the following (with Python 2.7.2 and Numpy 1.6.0 on Vista):

    In []: x= rand(1e5)
    In []: %timeit isnan(x.min())
    10000 loops, best of 3: 200 us per loop
    In []: %timeit isnan(x.sum())
    10000 loops, best of 3: 169 us per loop
    In []: %timeit isnan(dot(x, x))
    10000 loops, best of 3: 134 us per loop
    
    In []: x[5e4]= NaN
    In []: %timeit isnan(x.min())
    100 loops, best of 3: 4.47 ms per loop
    In []: %timeit isnan(x.sum())
    100 loops, best of 3: 6.44 ms per loop
    In []: %timeit isnan(dot(x, x))
    10000 loops, best of 3: 138 us per loop
    

    Thus, the really efficient way might be heavily dependent on the operating system. Anyway dot(.) based seems to be the most stable one.

提交回复
热议问题