# Numpy – Check If an Element is NaN

In this tutorial, we will look at how to check if an element in a Numpy array is a NaN (not a number) value or not with the help of some examples.

## How to test if an element is NaN or not in a Numpy array?

You can use the `numpy.isnan()` function to check (element-wise) if values in a Numpy array are NaN or not. The following is the syntax –

```# test for nan - pass scaler value or numpy array
np.isnan(a)```

If you apply the `numpy.isnan()` function to a scalar value, it returns a boolean value (True if the value is NaN otherwise False). If you apply it to an array, it returns a boolean array.

## Examples

Let’s now look at some examples of using the above function to test for NaN.

### Example 1 – Check if a value is NaN or not using `numpy.isnan()`

First, let’s pass scaler values to the `numpy.isnan()` function.

Let’s create two variables – one containing a NaN value and the other containing a non-Nan value respectively and then apply the `numpy.isnan()` function on each of these values.

```import numpy as np

# create two variables
a = 21
b = np.nan

# check if nan
print(np.isnan(a))
print(np.isnan(b))```

Output:

```False
True```

We get `False` as the output for the value `21` and `True` as the output for the NaN value.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

### Example 2 – Element-wise check for NaN in a Numpy array using `numpy.isnan()`

If you apply the `numpy.isnan()` function on an array, it will return a boolean array containing with `True` for values that are NaN and `False` for the non-Nan values.

Let’s create a 1-D array and apply the `numpy.isnan()` function to it.

```# create a numpy array
ar = np.array([1, 2, np.nan, 4, 5, np.nan, np.nan])
# element-wise check for nan value in ar
np.isnan(ar)```

Output:

`array([False, False,  True, False, False,  True,  True])`

We get a boolean array as an output. You can see that in the boolean array we get `True` for NaN values in the original array and `False` for the other values.

## Summary

In this tutorial, we looked at how we can use the `numpy.isnan()` function to check if an element is NaN or not in a Numpy array. Keep in mind that if you pass a scaler value, it returns a boolean value and if you pass a 1-D array it returns a boolean array.

You might also be interested in –