np.isnan: How to Check If Element has NaN Value in Python

The numpy isnan() function is used to test if the element is NaN(not a number) or not. The isnan() function is defined under numpy, imported as import numpy as np, and we can create the multidimensional arrays.

np.isnan

The np.isnan() function checks element-wise, whether NaN or not, returns the result as a boolean array. The np.isnan() method takes two parameters, out of which one is optional.

We can pass the arrays also to check whether the items present in the array belong to the NaN class or not. If it is NaN, the method returns True otherwise, False.

Syntax

numpy.isnan(input array or the scalar value, out(output array))

Parameters

The first parameter is the input array or the input for which we want to check whether it is NaN or not. The second one is the n-dimensional array, which is optional. Finally, it is the output array that is placed with the result.

Return Value

Numpy isnan() function returns a Boolean array, which has the result if we pass the array and Boolean value true or false if we pass a scalar value according to the value passed.

Example programs on isnan() method in Python

Write a program to show the isnan() function’s working in Python.

See the following code.

# app.py

import numpy as np

print("NaN value  - : ", np.isnan(933), "\n")  # Scalar Values

print("NaN value  - : ", np.isnan(444), "\n")

print("NaN value  - : ", np.isnan(np.inf), "\n")  # checking for infinity value

print("NaN value  - : ", np.isnan(np.NINF), "\n")

print("NaN value  - : ", np.isnan(np.nan))  # Checking for nan values

Output

python3 app.py
NaN value  - :  False

NaN value  - :  False

NaN value  - :  False

NaN value  - :  False

NaN value  - :  True

In this example, we have seen that bypassing two scalar values in the function isnan() we get False as it doesn’t represent any nan same with the infinity functions, but when we passed nan, it showed True.

Write a program to create an array using an arange() function and check for each value of the elements if it’s NaN or not.

See the following code.

# app.py

import numpy as np

arr = np.arange(24).reshape(6, 4)
print("List = ", arr)
print("\n")
print("Is NaN - ", np.isnan(arr))

Output

python3 app.py
List =  [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]


Is NaN -  [[False False False False]
 [False False False False]
 [False False False False]
 [False False False False]
 [False False False False]
 [False False False False]]

In this example, we can see that by creating a list of 24 elements, we have checked for each element if it contains a NaN value or not.

That’s it for this tutorial.

See also

Numpy isinf()

Numpy transpose

Numpy isscalar()

Numpy iscomplex()

Numpy save()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.