Check for Masked elements in NumPy Masked array
NumPy: Masked Arrays Exercise-20 with Solution
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.
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.
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://www.w3resource.com/python-exercises/numpy/check-for-masked-elements-in-numpy-masked-array.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics