The isnan() function of NumPy

Overview:

  • The function numpy.isnan()checks each element of a numpy array-like for the "not a number" property and returns True or False as the result. The results are returned as an ndarray containing Boolean values.
  • When the input is a scalar the return type is a single Boolean value.

Example:

# Example Python program that checks 
# the elements of an ndarray for "Not a Number"
import numpy

# Try making nans
elem1 = float('Inf') / float('Inf')
elem2 = float('Inf') - float('Inf')
elem3 = float('Inf') + 1
elem4 = numpy.inf - 1

# Create a numpy array and fill some of
# the elements with nan
nums = numpy.ndarray(shape = (2, 2))
nums[0][0] = elem1
nums[0][1] = elem2
nums[1][0] = elem3
nums[1][0] = elem4
print("Contents of the ndarray:")
print(nums)

# Check the ndarray for nans
print("Results of nan check:")
results = numpy.isnan(nums)
print(results)

Output:

Contents of the ndarray:

[[nan nan]

 [inf  0.]]

Results of nan check:

[[ True  True]

 [False False]]

 


Copyright 2024 © pythontic.com