# How to Check For NaN Values in Python

To check for NaN values in Python:

1. math.isnan(): It checks whether a value is NaN (Not a Number).
2. np.isnan(): It checks for NaN and returns the result as a boolean array.
3. pd.isna(): It detects missing values.

## Method 1: Using math.isnan()

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

NaN stands for Not A Number, a floating-point value representing missing data. People always confuse None and NaN because they look similar but are quite different.

The None is data it’s own(NoneType) used to define a null or no value. 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.

### 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``````

## Method 2: Using the np.isnan() method

The np.isnan() 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.

## Method 3: Using the pd.na() function

The pd.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.

## Method 4: 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. So 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 the NaN value.

That’s it.

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