w3resource

NumPy: Find the missing data in a given array

NumPy: Basic Exercise-43 with Solution

Write a NumPy program to find missing data in a given array.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np
 
# Creating a NumPy array 'nums' with provided values, including NaN (Not a Number)
nums = np.array([[3, 2, np.nan, 1],
                 [10, 12, 10, 9],
                 [5, np.nan, 1, np.nan]])

# Printing a message indicating the original array 'nums'
print("Original array:")
print(nums)

# Printing a message indicating finding the missing data (NaN) in the array using np.isnan()
# This function returns a boolean array of the same shape as 'nums', where True represents NaN values
print("\nFind the missing data of the said array:")
print(np.isnan(nums)) 

Sample Output:

Original array:
[[ 3.  2. nan  1.]
 [10. 12. 10.  9.]
 [ 5. nan  1. nan]]

Find the missing data of the said array:
[[False False  True False]
 [False False False False]
 [False  True False  True]]

Explanation:

The above example creates a NumPy array containing NaN values and prints a boolean array indicating which elements in the original array are NaN values.

nums = np.array(...): Here np.array(...) creates a 2D NumPy array named 'nums' with 3 rows and 4 columns. Some of the elements in the array are NaN (Not a Number).

print(np.isnan(nums)): Here np.isnan() function returns a boolean array of the same shape as 'nums', where each element indicates whether the corresponding element in 'nums' is NaN or not. Finally, it prints the resulting boolean array.

Python-Numpy Code Editor:

Previous: NumPy program to add elements in a matrix. If an element in the matrix is 0, we will not add the element below this element.
Next: NumPy program to check whether two arrays are equal (element wise) 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.