Open In App

Replace infinity with large finite numbers and fill NaN for complex input values using NumPy in Python

Last Updated : 03 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will cover how to fill Nan for complex input values and infinity values with large finite numbers in Python using NumPy.

Example:

Input: [complex(np.nan,np.inf)]

Output: [1000.+1.79769313e+308j]

Explanation: Replace Nan with complex values and infinity values with large finite.

numpy.nan_to_num method

The numpy.nan_to_num method is used to replace Nan values with zero, fills positive infinity and negative infinity values with a user-defined value or a big positive number. neginf is the keyword used for this purpose.

Syntax: numpy.nan_to_num(arr, copy=True)

Parameter:

  • arr: [array_like] Input data.
  • copy: [bool, optional] Default is True.

Return: New Array with the same shape as arr and dtype of the element in arr with the greatest precision.

Example 1:

In this example, an array is created using numpy.array() method which consists of np.nan and positive infinity. The shape, datatype, and dimensions of the array can be found by .shape, .dtype, and .ndim attributes. Here, np.nan is replaced with 1000 using the nan parameter, and n infinity is replaced with a large finite number.

Python3




# import package
import numpy as np
 
# Creating an array of imaginary numbers
array = np.array([complex(np.nan,np.inf)])
print(array)
 
# shape of the array is
print("Shape of the array is : ",array.shape)
 
# dimension of the array
print("The dimension of the array is : ",array.ndim)
 
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
 
# np.nan is replaced with 1000 and
#  infinity is replaced with a large positive number
print("After replacement the array is : ",
      np.nan_to_num(array,nan= 1000))


Output:

[nan+infj]
Shape of the array is :  (1,)
The dimension of the array is :  1
Datatype of our Array is :  complex128
After replacement the array is :  [1000.+1.79769313e+308j]

Example 2:

In this example, positive infinity is replaced with a user-defined value.

Python3




# import package
import numpy as np
 
# Creating an array of imaginary numbers
array = np.array([complex(np.nan,np.inf)])
print(array)
 
# shape of the array is
print("Shape of the array is : ",array.shape)
 
# dimension of the array
print("The dimension of the array is : ",array.ndim)
 
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
 
# np.nan is replaced with 1000 and
#  infinity is replaced with a large positive number
print("After replacement the array is : ",
      np.nan_to_num(array,nan= 1000))


Output:

[nan+infj]
Shape of the array is :  (1,)
The dimension of the array is :  1
Datatype of our Array is :  complex128
After replacement the array is :  [1000.+99999.j]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads