# Replace NaN with zero and infinity with large finite numbers for complex input values in Python

To replace NaN with zero and infinity with large finite numbers, use the numpy.nan_to_num() method in Python. The method returns, x, with the non-finite values replaced. If copy is False, this may be x itself. The 1st parameter is the input data. The 2nd parameter is copy, whether to create a copy of x (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True.

The 3rd parameter is nan, the value to be used to fill NaN values. If no value is passed then NaN values will be replaced with 0.0. The 4th parameter, posinf, a value to be used to fill positive infinity values. If no value is passed then positive infinity values will be replaced with a. The 5th parameter, neginfint, a value to be used to fill negative infinity values. If no value is passed then negative infinity values will be replaced with a very small (or negative) number.

## Steps

At first, import the required libraries −

import numpy as np

Creating a numpy array using the array() method −

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


Display the array −

print("Our Array...\n",arr)

Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)


Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

Get the Shape −

print("\nShape of our Array object...\n",arr.shape)


To replace NaN with zero and infinity with large finite numbers, use the numpy.nan_to_num() method in Python. The method returns, x, with the non-finite values replaced. If copy is False, this may be x itself −

print("\nResult...\n",np.nan_to_num(arr))

## Example

import numpy as np

# Creating a numpy array using the array() method
arr = np.array([complex(np.inf, np.nan), np.nan])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To replace NaN with zero and infinity with large finite numbers, use the numpy.nan_to_num() method in Python
print("\nResult...\n",np.nan_to_num(arr))

## Output

Our Array...
[inf+nanj nan +0.j]

Dimensions of our Array...
1

Datatype of our Array object...
complex128

Shape of our Array object...
(2,)

Result...
[1.79769313e+308+0.j 0.00000000e+000+0.j]