w3resource

Check for Masked elements in NumPy Masked array


20. Check for Presence of Masked Elements

Write a NumPy program that creates a masked array and checks if any masked elements are present.

Sample Solution:

Python Code:

import numpy as np
import numpy.ma as ma

# Create a 2D NumPy array of shape (5, 5) with random integers
array_2d = np.random.randint(0, 100, size=(5, 5))

# Define a condition to mask elements less than 20
condition = array_2d < 20

# Create a masked array from the 2D array using the condition
masked_array = ma.masked_array(array_2d, mask=condition)

# Check if any masked elements are present
has_masked_elements = masked_array.mask.any()

# Print the original array, the masked array, and whether any masked elements are present
print('Original 2D array:\n', array_2d)
print('Masked array (values < 20 are masked):\n', masked_array)
print('Any masked elements present?:', has_masked_elements)

Output:

Original 2D array:
 [[52 75 32 47 50]
 [39  1 45 63 62]
 [95 36 75 41 10]
 [40 59 51 76 11]
 [48 27 33 88 94]]
Masked array (values < 20 are masked):
 [[52 75 32 47 50]
 [39 -- 45 63 62]
 [95 36 75 41 --]
 [40 59 51 76 --]
 [48 27 33 88 94]]
Any masked elements present?: True

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
    • Imported numpy.ma as "ma" for creating and working with masked arrays.
  • Create 2D NumPy Array:
    • Create a 2D NumPy array named array_2d with random integers ranging from 0 to 99 and a shape of (5, 5).
  • Define Condition:
    • Define a condition to mask elements in the array that are less than 20.
  • Create Masked Array:
    • Create a masked array from the 2D array using ma.masked_array, applying the condition as the mask. Elements less than 20 are masked.
  • Check for Masked Elements:
    • Check if any masked elements are present in the masked array using the any method on the mask attribute.
  • Finally print the original 2D array, the masked array, and whether any masked elements are present.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to check if any elements in a masked array are masked using np.ma.is_masked and report the result.
  • Write a Numpy program to verify the presence of masked elements in a 2D masked array and then count them.
  • Write a Numpy program to create a masked array and then use logical operations to determine if all elements are unmasked.
  • Write a Numpy program to implement a custom function that returns a boolean indicating whether a masked array has any masked entries.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Apply Mathematical function to Unmasked elements in NumPy Masked array.

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.