How to replace NaN and infinite values in NumPy

Floating-point NumPy arrays can keep NaN, positive infinity, and negative infinity after imports, division, or overflow. Replacing those non-finite markers is useful when the array must keep its shape but downstream calculations, exports, or model inputs require finite numbers.

np.nan_to_num() handles all three markers in one pass. Explicit nan, posinf, and neginf arguments make the replacement policy visible and avoid the default infinity replacements, which use the largest or smallest finite value available for the dtype.

Pick replacement values that preserve the meaning of the data being cleaned. A missing sensor value, a positive overflow, and a negative overflow can mean different operational states, so count the non-finite values before and after replacement instead of only printing the cleaned array.

Steps to replace NaN and infinite values in NumPy:

  1. Create a script that replaces each non-finite value with an explicit finite value.
    nan-replace.py
    import numpy as np
     
    readings = np.array([18.5, np.nan, np.inf, -np.inf, 21.0])
     
    cleaned = np.nan_to_num(
        readings,
        nan=0.0,
        posinf=100.0,
        neginf=-100.0,
    )
     
    print("original:", readings)
    print("cleaned:", cleaned)
    print("input unchanged:", np.isnan(readings[1]) and np.isposinf(readings[2]))
    print("non-finite before:", np.count_nonzero(~np.isfinite(readings)))
    print("non-finite after:", np.count_nonzero(~np.isfinite(cleaned)))

    np.nan_to_num() returns a new array by default. Use copy=False only when later code should read the modified input array.

  2. Run the script and verify that the cleaned array has no non-finite values.
    $ python3 nan-replace.py
    original: [18.5  nan  inf -inf 21. ]
    cleaned: [  18.5    0.   100.  -100.    21. ]
    input unchanged: True
    non-finite before: 3
    non-finite after: 0

    The original array still contains NaN and inf because the replacement was written to cleaned. The final count confirms that cleaned contains only finite values.