Last Updated : 10 Jul, 2025
numpy.nan_to_num() function replaces NaN (Not a Number) with a specified numerical value (default is 0), and optionally converts positive or negative infinity to finite numbers.
Example:
Python
import numpy as np
a = np.array([1.0, np.nan, np.inf, -np.inf])
res = np.nan_to_num(a)
print(res)
[ 1.00000000e+000 0.00000000e+000 1.79769313e+308 -1.79769313e+308]
Explanation: By default, NaN is replaced with 0. Infinity values remain unchanged unless specified.
Syntaxnumpy.nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None)
Parameters:
Returns: This method returns an array with the same shape as x, where NaN, +inf and -inf are replaced with finite numbers.
ExamplesExample 1: Replace only NaNs with zero
Python
import numpy as np
a = np.array([np.nan, 2, 3])
res = np.nan_to_num(a)
print(res)
Explanation: NaN is replaced with 0, other values are unchanged.
Example 2: Replace NaN and infinite values
Python
import numpy as np
a = np.array([np.nan, np.inf, -np.inf, 5])
res = np.nan_to_num(a, nan=0, posinf=1000, neginf=-1000)
print(res)
[ 0. 1000. -1000. 5.]
Explanation: NaN → 0, +inf → 1000, -inf → -1000 and regular values like 5 remain unchanged.
Example 3: In-place modification with copy=False
Python
import numpy as np
a = np.array([np.nan, np.inf])
np.nan_to_num(a, nan=-1, posinf=9999, copy=False)
print(a)
[-1.000e+00 9.999e+03]
Explanation: The original array 'a' is modified directly without making a copy.
Related articles: Numpy
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4