AppDividend
Latest Code Tutorials

Python Check NaN: How to Check NaN Value in Python

0

NaN stands for Not A Number which is a floating-point value that represents missing data. People always confuse between None and NaN because it looks similar, but both are quite different.

The None is a data its own(NoneType) used to define a null value or no value at all. None is not the same as 0, False, or an empty string. While missing values are NaN in numerical arrays, they are None in object arrays.

Python Check NaN

To check NaN value in Python, 

  1. Use math.isnan() method
  2. Using np.isnan() function
  3. Use pd.isna() method
  4. Create your own function

Using math.isnan()

The math.isnan() is a built-in Python method that checks whether a value is NaN (Not a Number) or not. The isnan() method returns True if the specified value is a NaN. Otherwise, it returns False.

Syntax

math.isnan(num)

Arguments

The num is a required parameter which is the value to check.

Example

import math

test_data_a = 21
test_data_b = -19
test_data_c = float("nan")

print(math.isnan(test_data_a))
print(math.isnan(test_data_b))
print(math.isnan(test_data_c))

Output

False
False
True

Using np.nan() method

The np.nan() method tests the element-wise for NaN and returns the result as a boolean array.

import numpy as np

test_data_a = 21
test_data_b = -19
test_data_c = float("nan")

print(np.isnan(test_data_a))
print(np.isnan(test_data_b))
print(np.isnan(test_data_c))

Output

False
False
True

And the np.isnan() function returns True if it finds the NaN value.

Using pd.na() function

The isna() is a pandas function that can check if the value is NaN.

import pandas as pd

test_data_a = 21
test_data_b = -19
test_data_c = float("nan")

print(pd.isna(test_data_a))
print(pd.isna(test_data_b))
print(pd.isna(test_data_c))

Output

False
False
True

And the pd.na() function returns True if it finds the NaN value.

By Creating a function

The most common way to check for NaN values in Python is to check if the variable is equal to itself. If it is not, then it must be NaN value. Let’s create a function that checks the value to itself.

def isNaN(num):
    return num!= num

data = float("nan")
print(isNaN(data))

Output

True

We cannot compare the NaN value against itself. If it returns False, both values are the same, and the two NaNs are not the same. That is why from the above output, we can conclude that it is NaN value.

That is it for the how-to check nan value in the Python tutorial.

Leave A Reply

Your email address will not be published.

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