That's 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 NumPy itself is built) of these C functions the timings will be different.


The ufuncs for both refer to a built-in npy_ func (source (1.11.3)):

/**begin repeat1
 * #kind = isnan, isinf, isfinite, signbit, copysign, nextafter, spacing#
 * #func = npy_isnan, npy_isinf, npy_isfinite, npy_signbit, npy_copysign, nextafter, spacing#
 **/

And these functions are defined based on the presence of compile time constants (source (1.11.3)):

/* use builtins to avoid function calls in tight loops
 * only available if npy_config.h is available (= numpys own build) */
#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

/* only available if npy_config.h is available (= numpys own build) */
#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

So it might just be that in your case the np.isfinite has to do (much) more work than np.isnan. But it's equally likely that on another computer or with another build np.isfinite is faster or both are equally fast.

So, there is probably not a hard rule what the "fastest way" is. That just depends on too many factors. Personally I would just go with the np.isfinite because it can be faster (and isn't too much slower even in your case) and it makes the intention much clearer.


Just in case you're really into optimizing the performance, you can always do the negating in-place. That might decrease the 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)  # in-place
    return res

np.testing.assert_array_equal(~np.isfinite(arr), isnotfinite(arr))
np.testing.assert_array_equal(~np.isfinite(arr), np.isnan(arr - arr))

%timeit ~np.isfinite(arr)
# 3.73 ms ± 4.16 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit isnotfinite(arr)
# 2.41 ms ± 29.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.isnan(arr - arr)
# 12.5 ms ± 772 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Note also that the np.isnan solution is much slower on my computer (Windows 10 64bit Python 3.5 NumPy 1.13.1 Anaconda build)

Answer from MSeifert on Stack Overflow
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.isfinite.html
numpy.isfinite — NumPy v2.2 Manual
numpy.isfinite(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature]) = <ufunc 'isfinite'>#
🌐
W3Schools
w3schools.com › python › ref_math_isfinite.asp
Python math.isfinite() Method
The math.isfinite() method checks whether a number is finite or not.
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-isfinite-python
numpy.isfinite() in Python - GeeksforGeeks
March 8, 2024 - # Python Program illustrating # numpy.isfinite() method import numpy as geek # Returns True/False value for each element b = geek.arange(20).reshape(5, 4) print("\n",b) print("\nIs Finite : \n", geek.isfinite(b)) b = [[1j], [geek.inf]] print("\nIs Finite : \n", geek.isfinite(b))
🌐
Python
docs.python.org › 3 › library › math.html
math — Mathematical functions
math.isfinite(x)¶ · Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.) Added in version 3.2. math.isinf(x)¶ · Return True if x is a positive or negative infinity, and False otherwise. ...
Top answer
1 of 2
8

That's 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 NumPy itself is built) of these C functions the timings will be different.


The ufuncs for both refer to a built-in npy_ func (source (1.11.3)):

/**begin repeat1
 * #kind = isnan, isinf, isfinite, signbit, copysign, nextafter, spacing#
 * #func = npy_isnan, npy_isinf, npy_isfinite, npy_signbit, npy_copysign, nextafter, spacing#
 **/

And these functions are defined based on the presence of compile time constants (source (1.11.3)):

/* use builtins to avoid function calls in tight loops
 * only available if npy_config.h is available (= numpys own build) */
#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

/* only available if npy_config.h is available (= numpys own build) */
#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

So it might just be that in your case the np.isfinite has to do (much) more work than np.isnan. But it's equally likely that on another computer or with another build np.isfinite is faster or both are equally fast.

So, there is probably not a hard rule what the "fastest way" is. That just depends on too many factors. Personally I would just go with the np.isfinite because it can be faster (and isn't too much slower even in your case) and it makes the intention much clearer.


Just in case you're really into optimizing the performance, you can always do the negating in-place. That might decrease the 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)  # in-place
    return res

np.testing.assert_array_equal(~np.isfinite(arr), isnotfinite(arr))
np.testing.assert_array_equal(~np.isfinite(arr), np.isnan(arr - arr))

%timeit ~np.isfinite(arr)
# 3.73 ms ± 4.16 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit isnotfinite(arr)
# 2.41 ms ± 29.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.isnan(arr - arr)
# 12.5 ms ± 772 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Note also that the np.isnan solution is much slower on my computer (Windows 10 64bit Python 3.5 NumPy 1.13.1 Anaconda build)

2 of 2
0

Using numba accelerator in parallel no-python mode will be faster than the isnotfinite function and ~np.isfinite @MSeifert answer, which are among the fastest methods. If we prepare an example data using:

def data_(m, n, f):
    arr = np.random.random_integers(0, 10, m).astype(np.float64)
    n_ = np.random.permutation(m)
    arr[n_[:n//2]] = np.inf
    arr[n_[n // 2:n]] = -np.inf
    arr[n_[n:n+f]] = np.nan
    return arr

So, ~np.isfinite can be jitted using numba as:

import numpy as np
import numba as nb

@nb.njit(parallel=True)
def numba_(arr):
    res = np.empty(arr.shape[0], dtype=nb.boolean)
    for i in nb.prange(arr.shape[0]):
        res[i] = ~np.isfinite(arr[i])
    return res

@nb.njit(parallel=True)
def numba_full(arr):
    res = np.full(arr.shape[0], True)
    for i in nb.prange(arr.shape[0]):
        res[i] = ~np.isfinite(arr[i])
    return res

Benchmark on Google Collaboratory CPU (horizontal axis is referring to m for data_):
temporary link to colab

🌐
Medium
medium.com › @whyamit404 › understanding-numpy-isfinite-with-examples-7305ff609ce9
Understanding numpy.isfinite() with Examples | by whyamit404 | Medium
March 6, 2025 - These sneaky troublemakers can mess up calculations, break models, and even cause unexpected behavior in your code. This is where numpy.isfinite() comes in—it helps you identify which numbers are valid (finite) and which ones aren't in a dataset.
🌐
Data-apis
data-apis.org › array-api › 2025.12 › API_specification › generated › array_api.isfinite.html
isfinite — Python array API standard 2025.12 documentation
isfinite(x: array, /) → array¶ · Tests each element x_i of the input array x to determine if finite. Parameters: x (array) – input array. Should have a numeric data type. Returns: out (array) – an array containing test results. The returned array must have a data type of bool.
🌐
YouTube
youtube.com › watch
isfinite() function in Python | methods in python | function python | python for beginner | python - YouTube
In this comprehensive tutorial, we'll cover the following key points:1.isfinite() function in python for beginners in english.2.Function in Python for beginn...
Published   January 22, 2024
🌐
JAX Documentation
docs.jax.dev › en › latest › _autosummary › jax.numpy.isfinite.html
jax.numpy.isfinite — JAX documentation
>>> x = jnp.array([-1, 3, jnp.inf, jnp.nan]) >>> jnp.isfinite(x) Array([ True, True, False, False], dtype=bool) >>> jnp.isfinite(3-4j) Array(True, dtype=bool, weak_type=True)
Find elsewhere
🌐
Codecademy
codecademy.com › docs › python › math module › math.isfinite()
Python | Math Module | math.isfinite() | Codecademy
August 28, 2024 - The math.isfinite() function returns True when a number is finite and False otherwise. A finite number is neither infinite nor NaN. ... Looking for an introduction to the theory behind programming?
🌐
KooR.fr
koor.fr › Python › API › python › math › isfinite.wp
KooR.fr - Fonction isfinite - module math - Description de quelques librairies Python
acos acosh asin asinh atan atan2 ... isclose isfinite isinf isnan isqrt lcm ldexp lgamma log log10 log1p log2 modf nextafter perm pow prod radians remainder sin sinh sqrt sumprod tan tanh trunc ulp ... Vous êtes un professionnel et vous avez besoin d'une formation ? Programmation Python Les compléments ...
🌐
Google Translate
translate.google.com › translate
math — Mathematical functions — Python 3.14.6 documentation
math.isfinite(x)¶ · Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.) Added in version 3.2. math.isinf(x)¶ · Return True if x is a positive or negative infinity, and False otherwise. ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Infinity (inf) in Python | note.nkmk.me
August 11, 2023 - import numpy as np a = np.array([1, np.inf, -np.inf]) print(a) # [ 1. inf -inf] print(np.isinf(a)) # [False True True] print(np.isposinf(a)) # [False True False] print(np.isneginf(a)) # [False False True] print(np.isfinite(a)) # [ True False False]
🌐
Saturn Cloud
saturncloud.io › blog › python-numpy-typeerror-understanding-and-resolving-ufunc-isfinite-not-supported-for-the-input-types
ufunc 'isfinite' not supported for the input types . ...
July 23, 2023 - Saturn Cloud is the white-labeled control plane for GPU clouds: multi-tenant isolation, day-2 support, and integrated billing, running in your cloud under your brand.