It is hard to answer because np.isnan and np.isfinite can use different C functions depending on the build. And depending on the performance (which may well depend on the compiler, the system and how the NumPy function itself) from these C-functions, the timings will differ.
ufuncs for both refer to the built-in npy_ func ( source (1.11.3) ):
And these functions are determined based on the presence of compile-time constants ( source (1.11.3) ):
#if HAVE___BUILTIN_ISNAN #define npy_isnan(x) __builtin_isnan(x) #else #ifndef NPY_HAVE_DECL_ISNAN #define npy_isnan(x) ((x) != (x)) #else #if defined(_MSC_VER) && (_MSC_VER < 1900) #define npy_isnan(x) _isnan((x)) #else #define npy_isnan(x) isnan(x) #endif #endif #endif #if HAVE___BUILTIN_ISFINITE #define npy_isfinite(x) __builtin_isfinite(x) #else #ifndef NPY_HAVE_DECL_ISFINITE #ifdef _MSC_VER #define npy_isfinite(x) _finite((x)) #else #define npy_isfinite(x) !npy_isnan((x) + (-x)) #endif #else #define npy_isfinite(x) isfinite((x)) #endif #endif
Thus, it can only be that in your case np.isfinite should work (a lot) more than np.isnan . But equally likely, on another computer or with a different line, np.isfinite will be faster or both will be equally fast.
Thus, there is probably no hard and fast rule for what the “fastest way” is. It depends on too many factors. Personally, I would just go with np.isfinite , because it can be faster (and not too slow even in your case), and this makes the intention much clearer.
Just in case, when you really optimize performance, you can always do negation in place. This can reduce time and memory by avoiding one temporary array:
import numpy as np arr = np.random.rand(1000000) def isnotfinite(arr): res = np.isfinite(arr) np.bitwise_not(res, out=res)
Note also that the np.isnan solution on my computer is much slower (Windows 10 64-bit Python 3.5 NumPy 1.13.1 Anaconda build)
source share