# Test element-wise for NaN in Numpy

NumpyServer Side ProgrammingProgramming

#### Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

#### Data Analysis using NumPy and Pandas

19 Lectures 8 hours

#### Numpy with Python

Most Popular

12 Lectures 3 hours

To test element-wise for NaN, use the numpy.isnan() method in Python Numpy. Returns True where x is NaN, false otherwise. This is a scalar if x is a scalar. The condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.

## Steps

At first, import the required library −

import numpy as np

To test element-wise for NaN, use the numpy.isnan() method in Python Numpy.

Checking for numbers −

print("Check for NaN? ", np.isnan(1))
print("\nCheck for NaN? ", np.isnan(0))

Checking for float −

print("\nCheck for NaN? ", np.isnan(14.))
print("\nCheck for NaN? ", np.isnan(3.6))

Checking for NaN −

print("\nCheck for NaN? ", np.isnan(np.nan))
print("\nCheck for NaN? ", np.isnan(np.NAN))

Checking for infinity −

print("\nCheck for NaN? ", np.isnan(np.inf))
print("\nCheck for NaN? ", np.isnan(np.NINF))

Checking for log −

print("\nCheck for NaN? ", np.isnan(np.log(1)))
print("\nCheck for NaN? ", np.isnan(np.log(2)))

## Example

import numpy as np

# To test element-wise for NaN, use the numpy.isnan() method in Python Numpy

print("Check for NaN? ", np.isnan(1))
print("\nCheck for NaN? ", np.isnan(0))

# Checking for float
print("\nCheck for NaN? ", np.isnan(14.))
print("\nCheck for NaN? ", np.isnan(3.6))

# Checking for NaN
print("\nCheck for NaN? ", np.isnan(np.nan))
print("\nCheck for NaN? ", np.isnan(np.NAN))

# Checking for infinity
print("\nCheck for NaN? ", np.isnan(np.inf))
print("\nCheck for NaN? ", np.isnan(np.NINF))

# Checking for log
print("\nCheck for NaN? ", np.isnan(np.log(1)))
print("\nCheck for NaN? ", np.isnan(np.log(2)))

## Output

Check for NaN? False

Check for NaN? False

Check for NaN? False

Check for NaN? False

Check for NaN? True

Check for NaN? True

Check for NaN? False

Check for NaN? False

Check for NaN? False

Check for NaN? False