Check if a NumPy array contains any NaN value in Python

In this post, we will see how we can check if a NumPy array contains any NaN values or not in Python. I will show you how to use the isnan( ) method with some basic and interesting examples. We will be using the NumPy library in Python to use the isnan( ) method. You may come across this method while analyzing numerical data.

numpy.isnan( ) method in Python

The numpy.isnan( ) method is very useful for users to find NaN(Not a Number) value in NumPy array. It returns an array of boolean values in the same shape as of the input data. Returns a True wherever it encounters NaN, False elsewhere. The input can be either scalar or array. The method takes the array as a parameter whose elements we need to check.

syntax:
numpy.isnan(x)

How to check if a NumPy array contains any NaN value in Python

Some examples to show the use of isnan( ) method is shown below.

#Programm to show use of numpy.isnan() method 
    
import numpy as np
   
# Returns True/False value elementwise  
b = np.arange(25).reshape(5, 5) 
                 
print("\nIs NaN: \n", np.isnan(b)) 
    
c = [[1,2,3],  
     [np.nan,2,2]] 
print("\nIs NaN: \n", np.isnan(c)) 
 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 False]]

Is NaN: 
 [[False False False]
 [ True False False]]

In fields like Data Science and Machine learning, numerical data plays a very critical role as it helps in predictions and analysis. In such situations, it is very important to check whether your data consists of any NaN value or not.
Thus, we should also know how to replace the null values with some other standard/ideal values. A program to illustrate this process is shown below.

import numpy as np
     
b = [[1,2,3],[np.nan,np.nan,2]] 
arr = np.array(b)

print(arr)
print(np.isnan(arr))

x = np.isnan(arr)

#replacing NaN values with 0
arr[x] = 0
print("After replacing NaN values:")
arr
[[ 1.  2.  3.]
[nan nan  2.]]
[[False False False]

 [ True  True False]]
After replacing NaN values:
array([[1., 2., 3.]
[0., 0., 2.]])

Also read: Python math.isnan() with example

Leave a Reply