What is numpy.isnan() in Python?

Python’s numpy.isnan() tests if an element is NaNNot a Number or not. It tests an array element-wise and returns Boolean values.

Syntax

numpy.isnan() is declared as follows:

numpy.isnan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'isnan'>

In the syntax above, x is the non-optional parameter and the rest are optional parameters.

A universal function (ufunc) is a function that operates on ndarrays in an element-by-element fashion. The isnan() method is a universal function.

Parameters

The numpy.isnan() method takes the following compulsory parameter:

  • x [array-like] - input array.

The numpy.isnan() method takes the following optional parameters:

Parameter

Description

out

represents the location into which the output of the method is stored.

where

True value indicates that a universal function should be calculated at this position.

casting

controls the type of datacasting that should occur. The same_kind option indicates that safe casting or casting within the same kind should take place. 

order

controls the memory layout order of the output function. The option K means reading the elements in the order they occur in memory.

dtype

represents the desired data type of the array.

subok

decides if subclasses should be made or not. If True, subclasses will be passed through. 

Return value

numpy.isnan() returns a Boolean array.

  • It returns True if an element is NaN.

  • It returns False otherwise.

If x is scalar, the return type is also scalar.

Examples

The example below shows the use of numpy.isnan() on the elements a and b:

import numpy as np
a = np.nan
b = 20
print (np.isnan(a))
print (np.isnan(b))

The following example shows the use of numpy.isnan() on the array arr1:

import numpy as np
arr1 = np.array([1,2,np.nan, np.log(-3)])
print (np.isnan(arr1))
Copyright ©2024 Educative, Inc. All rights reserved