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.
This problem involves using NumPy to identify elements in an array that are NaN (Not a Number). The task is to write a program that checks each element of a given NumPy array to determine if it is NaN. This is important for data validation and cleaning, as NaN values can indicate missing or undefined data that may need to be handled or removed before performing further analysis. The program demonstrates how to use NumPy's functions to effectively detect NaN values within an 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))
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).
Visual Presentation:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/basic/numpy-basic-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics