Open In App

numpy.nan_to_num() in Python

Last Updated : 10 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Output
[ 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.

Syntax

numpy.nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None)

Parameters:

  • x: Input array (can be scalar, array-like).
  • copy: If True (default), returns a copy. If False, modifies the array in-place.
  • nan: Value to replace NaNs with (default is 0.0).
  • posinf: Value to replace positive infinity with (optional).
  • neginf: Value to replace negative infinity with (optional).

Returns: This method returns an array with the same shape as x, where NaN, +inf and -inf are replaced with finite numbers.

Examples

Example 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)

Output
[0. 2. 3.]

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)

Output
[    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)

Output
[-1.000e+00  9.999e+03]

Explanation: The original array 'a' is modified directly without making a copy.

Related articles: Numpy


Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy