w3resource

NumPy: Test element-wise for NaN of a given array

NumPy: Basic Exercise-7 with Solution

Write a NumPy program to test element-wise for NaN of a given array.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'a' containing elements 1, 0, NaN (Not a Number), and infinity
a = np.array([1, 0, np.nan, np.inf])

# Printing the original array 'a'
print("Original array")
print(a)

# Testing the given array 'a' element-wise for NaN (Not a Number) and printing the result
print("Test element-wise for NaN:")
print(np.isnan(a)) 

Sample Output:

Original array
[  1.   0.  nan  inf]
Test element-wise for NaN:
[False False  True False]                         

Explanation:

In the above code -

np.array([1, 0, np.nan, np.inf]) creates a NumPy array 'a' with the elements 1, 0, NaN (Not a Number), and Inf (Infinity).

print(np.isnan(a)): The np.isnan() function tests element-wise if the values in the array 'a' are NaN. The function returns a boolean array of the same shape as 'a', with True for NaN values and False for other values (1, 0, and Inf).

Pictorial Presentation:

NumPy: Test element-wise for NaN of a given array.

Python-Numpy Code Editor:

Previous: Test element-wise for positive or negative infinity.
Next: Test element-wise for complex number, real number of a given array. Also test if a given number is a scalar type or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.