Replace NaN with zero and fill positive infinity for complex input values in Python

The numpy.nan_to_num() function replaces NaN values with zero and infinity values with large finite numbers. This is particularly useful when working with complex numbers that contain non-finite values.

Syntax

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

Parameters

The function accepts the following parameters ?

  • x ? Input data (array-like)
  • copy ? Whether to create a copy (True) or replace in-place (False). Default is True
  • nan ? Value to replace NaN. Default is 0.0
  • posinf ? Value to replace positive infinity. Default is very large finite number
  • neginf ? Value to replace negative infinity. Default is very small finite number

Example with Complex Numbers

Let's create an array with complex numbers containing NaN and infinity values ?

import numpy as np

# Creating array with complex numbers containing NaN and infinity
arr = np.array([complex(np.inf, np.nan), np.nan])

# Display the original array
print("Original Array:")
print(arr)
print(f"Dimensions: {arr.ndim}")
print(f"Datatype: {arr.dtype}")
print(f"Shape: {arr.shape}")
Original Array:
[inf+nanj nan +0.j]
Dimensions: 1
Datatype: complex128
Shape: (2,)

Using nan_to_num() with Custom Values

Replace NaN with zero and positive infinity with a custom value ?

import numpy as np

arr = np.array([complex(np.inf, np.nan), np.nan])

# Replace NaN with 0 and positive infinity with 22222
result = np.nan_to_num(arr, posinf=22222)
print("Result with custom positive infinity:")
print(result)
Result with custom positive infinity:
[22222.+0.j     0.+0.j]

Multiple Replacement Values

You can specify different replacement values for NaN, positive infinity, and negative infinity ?

import numpy as np

# Array with various non-finite values
arr = np.array([np.inf, -np.inf, np.nan, 5.0])

# Replace with custom values
result = np.nan_to_num(arr, nan=999, posinf=1000, neginf=-1000)
print("Original:", arr)
print("Replaced:", result)
Original: [ inf -inf  nan   5.]
Replaced: [ 1000. -1000.   999.     5.]

In-Place Replacement

Use copy=False to modify the original array ?

import numpy as np

arr = np.array([np.inf, np.nan, 42.0])
print("Before:", arr)

# In-place replacement
np.nan_to_num(arr, copy=False, posinf=100)
print("After:", arr)
Before: [inf nan 42.]
After: [100.   0.  42.]

Conclusion

The numpy.nan_to_num() function effectively handles non-finite values in arrays, making it essential for data cleaning and numerical computations. Use custom replacement values via the nan, posinf, and neginf parameters for specific requirements.

Updated on: 2026-03-26T19:54:48+05:30

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements